`

条件变量(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


相关知识:
http://xingyunbaijunwei.blog.163.com/blog/static/765380672011112293354272/
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics