【发布时间】:2013-02-08 23:23:48
【问题描述】:
我编写了以下代码来了解使用 pthread 和互斥锁的事件排序。 main 函数创建两个线程,它们与函数 func1 和 func2 相关联。 func1 函数检查 count 的值并有条件地等待 func2 发出信号。函数 func2 递增 count,当 count 达到 50000 时,它会发出 func1 信号。 然后 func1 打印出 count 在当时是(或应该是)50000 的值。
但在实际输出中,除了 50000 之外,还打印了一些其他值。我不明白为什么会这样。我的想法是,当 func2 发出信号时,func1 会在 pthread_cond_wait 语句之后唤醒并执行,因此它应该只打印 50000。请指出我错在哪里应该改变什么以获得正确的输出?
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
pthread_mutex_t evmutex;
pthread_cond_t evcond;
char a;
int count;
int N = 50000;
void *func1()
{
while(1)
{
pthread_mutex_lock(&evmutex);
if(count < N)
{
pthread_cond_wait(&evcond,&evmutex);
printf("%d\n",count);
count = 0;
}
pthread_mutex_unlock(&evmutex);
}
}
void *func2()
{
while(1)
{
pthread_mutex_lock(&evmutex);
count++;
if(count == N)
{
pthread_cond_signal(&evcond);
}
pthread_mutex_unlock(&evmutex);
}
}
int main ()
{
pthread_t ptd1,ptd2;
pthread_mutex_init(&evmutex,NULL);
pthread_cond_init(&evcond,NULL);
count = 0;
pthread_create(&ptd1,NULL,func1,NULL);
pthread_create(&ptd2,NULL,func2,NULL);
pthread_exit(NULL);
pthread_mutex_destroy(&evmutex);
pthread_cond_destroy(&evcond);
return 0;
}
【问题讨论】: