我正在編寫一個程序來測試我對條件變量的理解。基本上,線程0檢查計數是否均勻,如果是,則遞增計數。如果沒有,那麼它表示線程1遞增計數變量。這個過程一直持續,直到計數達到15.這是我的代碼:使用pthreads的分段錯誤
#include <pthread.h>
#include <stdio.h>
#define numThreads 2
int count=0;
pthread_mutex_t count_mutex;
pthread_cond_t count_threshold_cv;
void *checkEven(void *threadId)
{ while(count<=15){
//lock the mutex
pthread_mutex_lock(&count_mutex);
printf("even_thread: thread_id=%d count=%d\n",threadId,count);
if(count%2==0){
count++;
}
else{
printf("Odd count found, signalling to odd thread\n");
pthread_cond_signal(&count_threshold_cv);
}
pthread_mutex_unlock(&count_mutex);
sleep(1);
}
}
void *checkOdd(void *threadId)
{
pthread_mutex_lock(&count_mutex); //obtain a lock
while(count<=15){
pthread_cond_wait(&count_threshold_cv, &count_mutex); //wait() relinquishes the lock
count++;
printf("odd_thread: thread_id=%d, count=%d\n",threadId,count);
}
pthread_mutex_unlock(&count_mutex);
pthread_exit(NULL);
}
int main()
{
pthread_t threads[numThreads];
int rc;
int a=0;
int b=0;
pthread_create(&threads[0], NULL, checkEven, (void *)a);
pthread_create(&threads[1], NULL, checkEven, (void *)b);
pthread_join(0,NULL);
pthread_join(1,NULL);
pthread_exit(NULL);
}
誰能告訴我爲什麼我收到分段錯誤(核心轉儲)誤差呢?我知道當一個進程試圖違反其他進程的地址空間時會發生這個錯誤,但是除此之外沒有其他的東西。可以有人請幫忙嗎?謝謝!
事情是偶數線程一旦計數爲奇數就調用信號。因此,奇數線程獲得鎖並在wait()調用之後繼續,並增加計數。然後解鎖並且偶數線程獲得鎖定,並且循環繼續。 –
你不能正確初始化你的'pthread_mutex_t'和'pthread_cond_t'。 – EOF
我認爲這不是它面臨的問題的原因。實際上,我通過傳遞0而不是線程[0]來搞亂join()的調用。 –