使用pthread

时间:2016-11-11 18:04:32

标签: c linux pthreads

我正在编写一个程序来测试我对条件变量的理解。基本上,线程0检查计数是否为偶数,如果是,则递增它。如果没有,则它发出线程1的信号,该线程1递增计数变量。这个过程一直持续到计数达到15.这是我的代码:

#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);
}

有人可以告诉我为什么我会收到分段错误(核心转储)错误吗?我知道当一个进程试图违反其他进程的地址空间时会发生此错误,但除此之外什么都没有。有人可以帮忙吗?谢谢!

1 个答案:

答案 0 :(得分:2)

您将0加到pthread_join作为您要加入的主题:

pthread_join(0,NULL);

你想:

pthread_join(threads[0],NULL);
pthread_join(threads[1],NULL);

你还有其他一些错误。首先,您的checkOdd代码会调用pthread_cond_wait,即使是该线程的回合。

您似乎不了解条件变量。具体来说,你似乎认为条件变量会以某种方式知道你正在等待的事情是否已经发生。它没有 - 条件变量是无状态的。你的工作是跟踪你在等待什么,以及它是否已经发生。