pthread_cond_wait例子分析

先来看一下pthread_cond_wait的语法:


条件变量   


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


1.   创建和注销   


条件变量和互斥锁一样,都有静态动态两种创建方式,静态方式使用PTHREAD_COND_INITIALIZER常量,如下:     

pthread_cond_t   cond=PTHREAD_COND_INITIALIZER     


动态方式调用pthread_cond_init()函数,API定义如下:     

int   pthread_cond_init(pthread_cond_t   *cond,   pthread_condattr_t   *cond_attr)     


尽管POSIX标准中为条件变量定义了属性,但在LinuxThreads中没有实现,因此cond_attr值通常为NULL,且被忽略。   


注销一个条件变量需要调用pthread_cond_destroy(),只有在没有线程在该条件变量上等待的时候才能注销这个条件变量,否则返回 EBUSY。因为Linux实现的条件变量没有分配什么资源,所以注销动作只包括检查是否有等待线程。API定义如下:     

int   pthread_cond_destroy(pthread_cond_t   *cond)     


2.   等待和激发   


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(),其中计时等待方式 如果在给定时刻前条件没有满足,则返回ETIMEOUT,结束等待,其中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()前的加锁动作对应。   


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


下面是一个例子:


#include <stdio.h>  

#include <unistd.h> 

#include <pthread.h>   


pthread_mutex_t    mutex;  

pthread_cond_t    cond;  


void *thread1(void *arg)  

{  

pthread_cleanup_push (pthread_mutex_unlock, &mutex);  


while(1) {  


pthread_mutex_lock (&mutex); 

printf ("thread1 is running\n");  

pthread_cond_wait (&cond, &mutex);  

printf ("thread1 applied the condition\n");  

pthread_mutex_unlock (&mutex);  

sleep (2);  

}  


pthread_cleanup_pop (0);  

}  


void *thread2(void *arg)  

{  

pthread_cleanup_push (pthread_mutex_unlock, &mutex);  

while(1) {  


pthread_mutex_lock (&mutex); 

printf ("thread2 is running\n");  

pthread_cond_wait (&cond, &mutex);  

printf ("thread2 applied the condition\n");  

pthread_mutex_unlock (&mutex);  

sleep (1);  

}  

pthread_cleanup_pop (0);  


int main(void)  

{  

pthread_t tid1, tid2;  


printf ("condition variable study! \n");  

pthread_mutex_init (&mutex, NULL);  

pthread_cond_init (&cond, NULL);  

pthread_create (&tid1, NULL, (void *) thread1, NULL);  

pthread_create (&tid2, NULL, (void *) thread2, NULL);  


do {  

pthread_cond_signal (&cond); 

sleep(2); 

} while (1);  


sleep (50);  

pthread_exit (0);  


[sunshine@localhost c_book]$ ./condition

condition variable study! 

thread1 is running

thread2 is running

thread1 applied the condition

thread1 is running

thread2 applied the condition

thread2 is running

thread1 applied the condition

thread1 is running

thread2 applied the condition

^C

[sunshine@localhost c_book]$ ./condition

condition variable study! 

thread1 is running

thread1 applied the condition

thread2 is running

thread1 is running

thread2 applied the condition

thread2 is running

thread1 applied the condition

thread1 is running

thread2 applied the condition


可以很清晰的看到,pthread_cond_wait的执行过程:

之前的pthread_mutex_lock对mutex加锁,pthread_cond_wait执行后进入等待激活队列并解锁,print后用pthread_mutex_unlock解锁。因此在thread1 执行pthread_cond_wait后thread2可以获得锁并打印 thread2 is running

pthread_cond_wait 与 pthread_mutex_lock pthread_mutex_unlock 使用的固定格式为


pthread_cleanup_push       防止取消点(pthread_cond_wait)非正常退出,而产生死锁。

pthread_mutex_lock

pthread_cond_wait              进入等待队列,并释放锁。退出时先重新获得锁,然后执行剩余代码。

pthread_mutex_unlock

pthread_cleanup_pop


需要说明的是pthread_cleanup_push 和 pthread_cleanup_pop

因为pthread_cond_wait 处为线程取消点,因此线程可以在该处取消,取消点在退出线程的时候会执行__pthread_cleanup_push函数 而这个函数的作用是重新对mutex加锁,因此会产生死锁。关于取消点可以google。

pthread_cond_timedwait函数是POSIX线程库中用于等待条件变量的函数之一。它可以在指定的时间内等待条件变量的状态发生变化。 下面是一个使用pthread_cond_timedwait函数的例子: ```c #include <stdio.h> #include <pthread.h> #include <unistd.h> pthread_mutex_t mutex; pthread_cond_t cond; void* thread_func(void* arg) { pthread_mutex_lock(&mutex); printf("Thread waiting...\n"); struct timespec timeout; clock_gettime(CLOCK_REALTIME, &timeout); timeout.tv_sec += 5; // 设置等待时间为5秒 int result = pthread_cond_timedwait(&cond, &mutex, &timeout); if (result == 0) { printf("Thread woken up!\n"); } else if (result == ETIMEDOUT) { printf("Thread timed out!\n"); } else { printf("Thread wait error!\n"); } pthread_mutex_unlock(&mutex); return NULL; } int main() { pthread_t thread; pthread_mutex_init(&mutex, NULL); pthread_cond_init(&cond, NULL); pthread_create(&thread, NULL, thread_func, NULL); sleep(2); // 等待2秒,确保子线程已经开始等待 pthread_mutex_lock(&mutex); printf("Main thread signaling...\n"); pthread_cond_signal(&cond); pthread_mutex_unlock(&mutex); pthread_join(thread, NULL); pthread_mutex_destroy(&mutex); pthread_cond_destroy(&cond); return 0; } ``` 在这个例子中,我们创建了一个子线程,子线程会在条件变量上等待。主线程等待2秒后,通过调用pthread_cond_signal函数来通知子线程条件变量的状态发生了变化。子线程在等待时间到达或者收到信号时会被唤醒,并打印相应的信息。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值