2
我對C中的系統編程非常陌生,我使用pthreads創建兩個線程來遞增計數器並顯示值。如果計數器值爲偶數,則線程1遞增,如果計數器值爲奇數,則線程2遞增。C Pthread:可能的死鎖,線程1在線程2退出時掛起
pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condition_var = PTHREAD_COND_INITIALIZER;
void *functionCount1();
void *functionCount2();
int count = 0;
#define COUNT_DONE 2
int main()
{
pthread_t thread1, thread2;
pthread_create(&thread1, NULL, &functionCount1, NULL);
pthread_create(&thread2, NULL, &functionCount2, NULL);
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
printf("Final count: %d\n",count);
exit(0);
}
void *functionCount1()
{
for(;;)
{
pthread_mutex_lock(&count_mutex);
pthread_cond_wait(&condition_var, &count_mutex);
count++;
printf("Counter value functionEven: %d\n",count);
pthread_mutex_unlock(&count_mutex);
if(count >= COUNT_DONE) {
printf("Thread 1: Exit condition reached.\n");
return(NULL);
}
}
}
void *functionCount2()
{
for(;;)
{
pthread_mutex_lock(&count_mutex);
if(count % 2 == 0)
{
pthread_cond_signal(&condition_var);
}
else
{
count++;
printf("Counter value functionOdd: %d.\n",count);
}
pthread_mutex_unlock(&count_mutex);
if(count >= COUNT_DONE) {
printf("Thread 2: Exit condition reached.\n");
return(NULL);
}
}
}
從我可以看到,問題是線程2達到它首先存在狀態,而讓線程1掛。
Counter value functionEven: 1
Counter value functionOdd: 2.
Thread 2: Exit condition reached.
(This is where it hangs, I have to press Ctrl-C to end)^C
當線程2達到其退出條件時,我試過另一個鎖,並且只有當線程1存在條件被調用時才解鎖它。但這似乎沒有做任何事情。
pthread_mutex_t mutex2 = PTHREAD_MUTEX_INITIALIZER;
if(count >= COUNT_DONE) {
printf("Thread 1: Exit condition reached.\n");
pthread_mutex_unlock(&mutex2);
return(NULL);
}
if(count >= COUNT_DONE) {
pthread_mutex_lock(&mutex2);
printf("Thread 2: Exit condition reached.\n");
return(NULL);
}
正確數量的最終解決方案。
以下答案幫了很大忙,解決了主要問題。
pthread_cond_wait(&condition_var, &count_mutex);
if(count >= COUNT_DONE) {
return(NULL);
}
count++;
printf("Counter value functionEven: %d\n",count);
由於在兩個if語句中變量數不受保護,因此您有數據競爭。因此行爲是不確定的。我的意思是發佈一個完整的答案,但我不確定代碼的意圖是什麼。 – 2501