linux c++多线程互斥锁和信号量简单实例

#include
#include

using namespace std;
int num = 0;
pthread_mutex_t lock;
pthread_cond_t threadADo;
pthread_cond_t threadBDo;

void *doThreadA(void *a)//只输出偶数
{
for(int i = 0; i<100; i++)
{
pthread_mutex_lock(&lock);
if(num%2 != 0)
pthread_cond_wait(&threadADo, &lock);//等待
cout << "A do,num:" << num << endl;
num++;
pthread_cond_signal(&threadBDo);//发信号
pthread_mutex_unlock(&lock);
}

return (void*)0;
}
void *doThreadB(void *a)//只输出奇数
{
while(1)
{
pthread_mutex_lock(&lock);
if(num%2 == 0)
pthread_cond_wait(&threadBDo, &lock);//等待
cout << "B do,num:" << num << endl;
num++;
pthread_cond_signal(&threadADo);//发信号,解除等待threadADo的阻塞线程
pthread_mutex_unlock(&lock);
}

return (void*)0;
}

int main()
{
pthread_t a, b;
pthread_mutex_init(&lock, NULL);
pthread_cond_init(&threadADo, NULL);
pthread_cond_init(&threadBDo, NULL);
pthread_create(&a, NULL, doThreadA, 0);
pthread_create(&b, NULL, doThreadB, 0);
void *recycle;
pthread_join(a, &recycle);//回收资源
pthread_join(b, &recycle);
return 0;

}


你可能感兴趣的:(C/C++)