我正在编写一个程序来测试我对条件变量的理解。基本上,线程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()的调用。 –