为了让线程在等待满足某些条件时使线程进入睡眠状态,一旦条件满足,就唤醒因等待满足特定条件而睡眠的线程
关键代码
- 条件变量的初始化
pthread_cond_t qready = PTHREAD_COND_INITIALIZER;
- 条件变量的阻塞以及唤醒
pthread_cond_wait(&qready, &qlock);
pthread_cond_signal(&qready);
整体代码
代码思路:主函数首先创建线程func1由于x<y,因此信号量qready被阻塞,同时解开qlock (为了让func2正常运行),接着函数首先创建线程func2,在线程func2中xy被改变,因此信号量qready被激活。
#include "pch.h"
#include<stdio.h>
#include <pthread.h>
#include <windows.h>
#include <iostream>
#pragma comment(lib, "pthreadVC2.lib")
using namespace std;
/*信号量*/
pthread_cond_t qready = PTHREAD_COND_INITIALIZER;
pthread_mutex_t qlock = PTHREAD_MUTEX_INITIALIZER;
int x = 10;
int y = 20;
void *func1(void *arg) {
printf("func1 start\n");
pthread_mutex_lock(&qlock);
while (x < y)
{
pthread_cond_wait(&qready, &qlock);
}
pthread_mutex_unlock(&qlock);
Sleep(3000);
printf("func 1 end\n");
return 0;
}
void *func2(void *arg) {
printf("func 2 start\n");
pthread_mutex_lock(&qlock);
x = 20;
y = 10;
cout << "has change x and y\n";
pthread_mutex_unlock(&qlock);
if (x > y)
{
pthread_cond_signal(&qready);
}
printf("func 2 end\n");
return 0;
}
int main(int argc, char **argv)
{
pthread_t tid1, tid2;
int iRet;
iRet = pthread_create(&tid1, NULL, func1, NULL);
if (iRet) {
cout << "pthread 1 create error\n";
return iRet;
}
Sleep(2000);
iRet = pthread_create(&tid2, NULL, func2, NULL);
if (iRet) {
cout << "pthread 2 create error\n";
return iRet;
}
Sleep(5000);
return 0;
}
/*信号量*/