linux 条件变量简单讲解 – Denny

条件变量使我们可以睡眠等待某种条件出现。条件变量是利用线程间共享的全局变量进行同步的一种机制,主要包括两个动作:一个线程等待"条件变量的条件成立"而挂起;另一个线程使"条件成立"(给出条件成立信号)。为了防止竞争,条件变量的使用总是和一个互斥锁结合在一起。

条件变量类型为pthread_cond_t

创建和注销条件变量和互斥锁一样,都有静态动态两种创建方式,静态方式使用PTHREAD_COND_INITIALIZER常量,如下:pthread_cond_tcond=PTHREAD_COND_INITIALIZER动态方式调用pthread_cond_init()函数,API定义如下:intpthread_cond_init(pthread_cond_t*cond,pthread_condattr_t*cond_attr)尽管POSIX标准中为条件变量定义了属性,但在LinuxThreads中没有实现,因此cond_attr值通常为NULL,且被忽略。注销一个条件变量需要调用pthread_cond_destroy(),只有在没有线程在该条件变量上等待的时候才能注销这个条件变量,否则返回EBUSY。API定义如下:intpthread_cond_destroy(pthread_cond_t*cond)

等待和激发intpthread_cond_wait(pthread_cond_t*cond,pthread_mutex_t*mutex)intpthread_cond_timedwait(pthread_cond_t*cond,pthread_mutex_t*mutex,conststructtimespec*abstime)等待条件有两种方式:无条件等待pthread_cond_wait()和计时等待pthread_cond_timedwait(),其中计时等待方式如果在给定时刻前条件没有满足,则返回ETIMEOUT,结束等待,其中abstime以与time()系统调用相同意义的绝对时间形式出现,0表示格林尼治时间1970年1月1日0时0分0秒。使用绝对时间而非相对时间的优点是。如果函数提前返回(很可能因为捕获了一个信号,)无论哪种等待方式,都必须和一个互斥锁配合,以防止多个线程同时请求pthread_cond_wait()(或pthread_cond_timedwait(),下同)的竞争条件(RaceCondition)。mutex互斥锁必须是普通锁(PTHREAD_MUTEX_TIMED_NP)或者适应锁(PTHREAD_MUTEX_ADAPTIVE_NP),且在调用pthread_cond_wait()前必须由本线程加锁(pthread_mutex_lock()),而在更新条件等待队列以前,mutex保持锁定状态,并在线程挂起进入等待前解锁。在条件满足从而离开pthread_cond_wait()之前,mutex将被重新加锁,以与进入pthread_cond_wait()前的加锁动作对应。激发条件有两种形式,pthread_cond_signal()激活一个等待该条件的线程,存在多个等待线程时按入队顺序激活其中一个;而pthread_cond_broadcast()则激活所有等待线程。

其他pthread_cond_wait()和pthread_cond_timedwait()都被实现为取消点,因此,在该处等待的线程将立即重新运行,在重新锁定mutex后离开pthread_cond_wait(),然后执行取消动作。也就是说如果pthread_cond_wait()被取消,mutex是保持锁定状态的,因而需要定义退出回调函数来为其解锁。以下示例集中演示了互斥锁和条件变量的结合使用,以及取消对于条件等待动作的影响。在例子中,有两个线程被启动,并等待同一个条件变量,如果不使用退出回调函数(见范例中的注释部分),则tid2将在pthread_mutex_lock()处永久等待。如果使用回调函数,则tid2的条件等待及主线程的条件激发都能正常工作。

#include <stdio.h>;#include <pthread.h>;#include <unistd.h>;pthread_mutex_t mutex;pthread_cond_t  cond;void * child1(void *arg){        pthread_cleanup_push(pthread_mutex_unlock,&mutex);  /* comment 1 */        while(1){          printf("thread 1 get running \n");        printf("thread 1 pthread_mutex_lock returns %d\n",pthread_mutex_lock(&mutex)); pthread_cond_wait(&cond,&mutex);// 这里正在等待信号,此时条件变量必须与一个互斥锁关联,          printf("thread 1 condition applied\n");          pthread_mutex_unlock(&mutex);          sleep(5);    }        pthread_cleanup_pop(0);     /* comment 2 */}

int main(void){        int tid1,tid2;        printf("hello, condition variable test\n");        pthread_mutex_init(&mutex,NULL);        pthread_cond_init(&cond,NULL);        pthread_create(&tid1,NULL,child1,NULL);        pthread_create(&tid2,NULL,child2,NULL);        do{        sleep(2);                   /* comment 4 */                pthread_cancel(tid1);       /* comment 5 */                sleep(2);                   /* comment 6 */        pthread_cond_signal(&cond);                //发送信号    }while(1);          sleep(100);        pthread_exit(0);}

旅行是一种病,当你把身边的人都传染了,

linux 条件变量简单讲解 – Denny

相关文章:

你感兴趣的文章:

标签云: