首先,我還是 posix 編程的新手并且仍然理解基本概念。我仍然不太清楚如何pthread_mutex_lock
pthread_mutex_unlock作業。
#include <unistd.h>
#include <errno.h>
#include <stdlib.h>
#include <pthread.h>
#inlcude <stdio.h>
pthread_mutex_t_mtx;
void* routine(void* i){
int j;
for(j = 0; j < 1000000; j){
pthread_mutex_lock(&mtx);
printf("Inside thread %d\n", i);
pthread_mutex_unlock(&mtx);
}
return NULL;
}
int main()
{
pthread_t th[3];
int i;
pthread_mutex_init(&mtx, NULL);
for(i = 1; i <= 2; i)
{
if(pthread_create(th i, NULL, routine, i){
perror(NULL); return 1;
}
}
for(i = 1; i <=2; i)
pthread_join(th[i], NULL);
return 0;
}
上述程式的正確輸出應該是什么?我認為由于互斥鎖的鎖定和解鎖會有 2000000 次迭代,但我不太清楚它們的完成順序。第一個執行緒是否執行 for 的前 1000000 步?它甚至執行 20000000 中的第一個嗎?或者這是由一個更混亂的秩序發生的?
uj5u.com熱心網友回復:
假設互斥鎖是全域互斥鎖,您將收到 2000000 條訊息,每個執行緒有 1000000 條訊息。這些順序是隨機的,但是它們不會相互干擾,因為每個列印都受互斥鎖保護
編輯:我剛剛注意到,您在創建下一個執行緒之前加入。因此,首先會有第一個執行緒的所有訊息,然后是第二個執行緒的所有訊息。在這種情況下,互斥鎖根本不起作用。排序的原因很簡單,因為您不會同時運行一個以上的作業執行緒。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/370874.html
