条件变量

为了让线程在等待满足某些条件时使线程进入睡眠状态,一旦条件满足,就唤醒因等待满足特定条件而睡眠的线程

    关键代码

  •         条件变量的初始化
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;
}

/*信号量*/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值