c++ - 不可预测的线程行为

标签 c++ pthreads

我正在尝试实现这个关于如何使用 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/

相关文章:

c# - 这可能与 activex 控件有关吗?

c++ - C++中 'glue'两个类实现的正确方法

c++ - 需要维护秩序的多线程作业

c++ - cocos2d-x如何支持多线程

c++ - 如何通过 boost.python 或 python/c api 调用 python 字节码文件

c++ - 从 2D vector 中的每一行添加最大元素,使得行元素 $A_i$ 小于 $A_(i+1)$

c++ - 在 C++ 中为 SQL 转义字符串

c - 从 C 中的 main 返回时,正在运行的线程会发生什么?

C++:pthread_create 上的段错误

C++ 简单线程启动问题