• pthread_cond_wait


    int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex)
    int pthread_cond_timedwait(pthread_cond_t *cond, pthread_mutex_t *mutex, const struct timespec *abstime)
    等待条件有两种方式:条件等待pthread_cond_wait()和计时等待pthread_cond_timedwait(),其中计时等待方式如果在给定时刻前条件没有满足,则返回ETIMEDOUT,结束等待,其中abstime以与time()系统调用相同意义的绝对时间形式出现,0表示格林尼治时间1970年1月1日0时0分0秒。
    无论哪种等待方式,都必须和一个互斥锁配合,以防止多个线程同时请求pthread_cond_wait()(或pthread_cond_timedwait(),下同)的竞争条件(Race Condition)。mutex互斥锁必须是普通锁(PTHREAD_MUTEX_TIMED_NP)或者适应锁(PTHREAD_MUTEX_ADAPTIVE_NP),且在调用pthread_cond_wait()前必须由本线程加锁(pthread_mutex_lock()),而在更新条件等待队列以前,mutex保持锁定状态,并在线程挂起进入等待前解锁。在条件满足从而离开pthread_cond_wait()之前,mutex将被重新加锁,以与进入pthread_cond_wait()前的加锁动作对应。

    int pthread_cond_signal(pthread_cond_t *cond)
    int pthread_cond_broadcast(pthread_cond_t *cond)
    激发条件有两种形式,pthread_cond_signal()激活一个等待该条件的线程,存在多个等待线程时按入队顺序激活其中一个;而pthread_cond_broadcast()则激活所有等待线程。

    #include <unistd.h>
    #include <pthread.h>
    #include <stdio.h>
    
    pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
    pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
    pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
    
    void* thread_1(void *a)
    {
        while(1)
        {
            pthread_mutex_lock(&lock);
            pthread_cond_wait(&cond, &lock);
            printf("1111111111111
    ");
            pthread_mutex_unlock(&lock);
            sleep(1);
        }
    }
    
    void* thread_2(void *a)  
    {  
        while(1)
        {
            pthread_mutex_lock(&lock);
            printf("222222222
    ");
            pthread_mutex_unlock(&lock);
            pthread_cond_signal(&cond);
            sleep(2);
        }
    }  
    
    void* thread_3(void *a)
    {
        while(1)
        {
            pthread_mutex_lock(&mutex);
            printf("333333333
    ");
            pthread_mutex_unlock(&mutex);
            sleep(3);
        }
    }
    
    void* thread_4(void *a)  
    {  
        while(1)
        {
            pthread_mutex_lock(&mutex);
            printf("222222222
    ");
            pthread_mutex_unlock(&mutex);
            sleep(4);
        }
    }  
    
    int main()
    {
        int i;
        pthread_t ths[2];
    
    #if 1
        pthread_create(&ths[0], NULL,  thread_1, 0);
        pthread_create(&ths[1], NULL,  thread_2, 0);
    #else    
        //pthread_create(&ths[0], NULL,  thread_3, 0);
        //pthread_create(&ths[1], NULL,  thread_4, 0);
    #endif
        
        for(i = 0; i < 2; ++ i){
            pthread_join(ths[i], NULL);
        }
        printf("Play End!
    ");
        return 0;
    }
  • 相关阅读:
    算法洗脑系列(8篇)——第五篇 分治思想
    算法洗脑系列(8篇)——第七篇 动态规划
    算法洗脑系列(8篇)——第四篇 枚举思想
    8天学通MongoDB——第二天 细说增删查改
    12篇学通C#网络编程——第一篇 基础之进程线程
    算法系列15天速成——第十五天 图【下】(大结局)
    算法洗脑系列(8篇)——第一篇 递推思想
    8天学通MongoDB——第三天 细说高级操作
    8天学通MongoDB——第四天 索引操作
    算法洗脑系列(8篇)——第八篇 概率思想
  • 原文地址:https://www.cnblogs.com/soul-stone/p/6736126.html
Copyright © 2020-2023  润新知