2013-02-26 131 views
3

據我所知,互斥鎖應該鎖定一次,然後阻止其他人,直到釋放,就像這樣。互斥鎖無數次

enter image description here

但是我的代碼,這似乎是多線程鎖定相同的互斥。我有一個10線程池,所以肯定9應該阻止,1應該鎖定。但我得到這個輸出。

Thread 0 got locked 
Thread 1 got locked 
Thread 3 got locked 
Thread 4 got locked 
Thread 2 got locked 
Thread 5 got locked 
Thread 6 got locked 
Thread 7 got locked 
Thread 8 got locked 
Thread 9 got locked 

我的互斥體在* .c文件的頂部全局定義,

pthread_mutex_t queuemutex = PTHREAD_MUTEX_INITIALIZER; 

這裏是相關的代碼段。

//In the main function which creates all the threads 
int k; 
for (k = 0; k < POOLSIZE; k++) { 
    pthread_t thread; 
    threadinformation *currentThread = (threadinformation *)malloc(sizeof(threadinformation)); 
    currentThread->state = (int *)malloc(sizeof(int)); 
    currentThread->state[0] = 0; 
    currentThread->currentWaiting = currentWaiting; 
    currentThread->number = k; 
    threadArray[k] = currentThread; 
    pthread_create(&thread, NULL, readWriteToClient, threadArray[k]); 
    currentThread->thread = thread; 
    joinArray[k] = thread; 
} 

這裏是所有10個線程似乎鎖定的代碼段。

pthread_mutex_lock(&queuemutex); 

fprintf(stderr,"Thread %d got locked \n",threadInput->number); 

while((threadInput->currentWaiting->status) == 0){ 
    pthread_cond_wait(&cond, &queuemutex); 
    fprintf(stderr,"Thread %d got signalled \n",threadInput->number); 
} 

connfd = threadInput->currentWaiting->fd; 
threadInput->currentWaiting->status = 0; 
pthread_cond_signal(&conncond); 
pthread_mutex_unlock(&queuemutex); 
+0

'int retcode = pthread_mutex_lock(&queuemutex); assert(retcode == 0);' – Sebivor 2013-02-26 12:44:44

+1

什麼是'currentWaiting'?或者更具體地說,'currentWaiting-> status'的初始值是多少? – Hasturkun 2013-02-26 12:49:57

回答

7

我的精神力量表明,currentWaiting->status最初0

由於這種情況,您的代碼將進入while循環並等待條件變量。

等待條件變量解鎖互斥鎖,直到等待完成,允許其他線程獲取它。

+0

+1這必須是正確的。 [pthread_cond_wait:](http://linux.die.net/man/3/pthread_cond_wait)'這些函數以原子方式釋放互斥鎖並導致調用線程在條件變量cond上被阻塞;' – Mike 2013-02-26 13:04:30

+0

非常棒,否則互斥體邏輯就沒有意義了。 所以,一般來說,在代碼塊被多線程運行時,在互斥體內部有cond_wait是否可行? 它似乎不會導致我的程序的問題,這只是令人沮喪! :) – 2013-02-26 13:09:17

+0

完美的答案。你從哪裏得到你的精神病。權力? ;) – didierc 2013-02-26 13:13:11