条件变量(cond)


#include <pthread.h>
#include <unistd.h>
#include <iostream>
using namespace std;

int * g_ptr = NULL;
pthread_cond_t g_cond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t g_mutex;

void* testCond(void*)
{
pthread_mutex_lock(&g_mutex);
if(g_ptr==NULL){
pthread_cond_wait(&g_cond,&g_mutex);//block->unlock->wait,返回时再次:lock
}
cout << "wait finished" << endl;
pthread_mutex_lock(&g_mutex);
pthread_detach(pthread_self());
return 0;
}

int main()
{
if(pthread_mutex_init(&g_mutex,NULL)!=0)
{
pthread_mutex_destroy(&g_mutex);
return -1;
}
pthread_t pid;
pthread_create(&pid,NULL,testCond,NULL);
sleep(1);
//发出通知
pthread_cond_signal(&g_cond);
g_ptr = new int(1);
sleep(2);
}

wait finished


等待超时

#include <pthread.h>
#include <unistd.h>
#include <iostream>
#include <sys/time.h>
using namespace std;

int * g_ptr = NULL;
pthread_cond_t g_cond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t g_mutex;

void* testCond(void*)
{
pthread_mutex_lock(&g_mutex);
if(g_ptr==NULL)
{
struct timespec timeEnd;
struct timeval timeNow;
gettimeofday(&timeNow,NULL);
//如果2秒钟没有唤醒则不等待
timeEnd.tv_sec = timeNow.tv_sec+2;
//block->unlock->wait,返回时再次:lock
pthread_cond_timedwait(&g_cond,&g_mutex,&timeEnd);
}
cout << "wait finished" << endl;
pthread_mutex_lock(&g_mutex);
pthread_detach(pthread_self());
return 0;
}

int main()
{
if(pthread_mutex_init(&g_mutex,NULL)!=0)
{
pthread_mutex_destroy(&g_mutex);
return -1;
}
pthread_t pid;
pthread_create(&pid,NULL,testCond,NULL);
cout << "creat thread" << endl;
sleep(5);
//发出通知
cout << "send signal" << endl;
pthread_cond_signal(&g_cond);
g_ptr = new int(1);
sleep(5);
}

creat thread
wait finished
send signal


相关知识:
[url]http://xingyunbaijunwei.blog.163.com/blog/static/765380672011112293354272/[/url]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值