我正在尝试实现这个关于如何使用 pthread 库同步线程的简单示例:
#include <iostream>
#include <pthread.h>
using namespace std ;
static pthread_mutex_t locker;
pthread_cond_t cond;
volatile bool ok=false;
void *func2(void *data)
{
int i;
for(i=0;i<100;i++)
{
pthread_mutex_lock (&locker);
cout << "1";
pthread_mutex_unlock(&locker);
if(i==10)
{
ok=true;
pthread_cond_signal(&cond);
}
}
pthread_exit(0);
}
void *fun1(void *data)
{
int i;
for(i=0;i<100;i++)
{
if(ok==false){
pthread_cond_wait(&cond, &locker);
}
pthread_mutex_lock (&locker);
cout << "2";
pthread_mutex_unlock(&locker);
}
pthread_exit(0);
}
int main(void)
{
pthread_t thread1, thread2;
void *retour_thread;
pthread_mutex_init (&locker, NULL);
pthread_cond_init(&cond, NULL);
if(pthread_create (&thread1, NULL, fun1, NULL) < 0)
{
cout << "problem thread";
exit(1);
}
if(pthread_create (&thread2, NULL, func2, NULL) < 0)
{
cout << "problem thread";
exit(1);
}
(void)pthread_join(thread1,&retour_thread);
(void)pthread_join(thread2,&retour_thread);
return 0;
}
我应该看到的是 func1 等到条件 (ok==true) 然后处理 func2...但是我得到的是不可预测的并且没有同步!!!
任何帮助和提前感谢
最佳答案
- 条件的第 1 条规则 变量:WAITING条件变量 持有锁时(等待时 锁将被释放)
- 条件的第 2 条规则 变量:总是使用“while 条件,等待条件 变量”(避免虚假信号)
关于c++ - 不可预测的线程行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4375542/