pthread_cond_broadcast()

本文详细介绍了pthread_cond_timedwait函数的使用方法及其在多线程编程中的应用。通过对比sleep函数,演示了如何利用该函数优雅地控制线程的等待与唤醒,解决了线程及时响应的问题。

pthread_cond_timedwait()函数阻塞住调用该函数的线程,等待由cond指定的条件被触发(pthread_cond_broadcast() or pthread_cond_signal())。

当pthread_cond_timedwait()被调用时,调用线程必须已经锁住了mutex。函数pthread_cond_timedwait()会对mutex进行【解锁和执行对条件的等待】(原子操作)。这里的原子意味着:解锁和执行条件的等待是原则的,一体的。(In this case, atomically means with respect to the mutex and the condition variable and other access by threads to those objects through the pthread condition variable interfaces.)

如果等待条件满足或超时,或线程被取消,调用线程需要在线程继续执行前先自动锁住mutex,如果没有锁住mutex,产生EPERM错误。即,该函数返回时,mutex已经被调用线程锁住。

等待的时间通过abstime参数(绝对系统时间,过了该时刻就超时)指定,超时则返回ETIMEDOUT错误码。开始等待后,等待时间不受系统时钟改变的影响。

尽管时间通过秒和纳秒指定,系统时间是毫秒粒度的。需要根据调度和优先级原因,设置的时间长度应该比预想的时间要多或者少点。可以通过使用系统时钟接口gettimeofday()获得timeval结构体。


多线程编程中,线程A循环计算,然后sleep一会接着计算(目的是减少CPU利用率);存在的问题是,如果要关闭程序,通常选择join线程A等待线程A退出,可是我们必须等到sleep函数返回,该线程A才能正常退出,这无疑减慢了程序退出的速度。当然,你可以terminate线程A,但这样做很不优雅,且会存在一些未知问题。采用pthread_cond_timedwait(pthread_cond_t * cond, pthread_mutex_t *mutex, const struct timespec * abstime)可以优雅的解决该问题,设置等待条件变量cond,如果超时,则返回;如果等待到条件变量cond,也返回。本文暂不将内部机理,仅演示一个demo

  1. static unsigned char flag = 1;  
  2. void * thr_fn(void * arg)  
  3. {  
  4.     while (flag)  
  5.     {  
  6.         printf(“thread sleep 10 second\n”);  
  7.         sleep(10);  
  8.     }  
  9.     printf(“thread exit\n”);  
  10. }  
  11.   
  12. int main()  
  13. {  
  14.     pthread_t thread;  
  15.     if (0 != pthread_create(&thread, NULL, thr_fn, NULL))  
  16.     {  
  17.         printf(“error when create pthread,%d\n”, errno);  
  18.         return 1;  
  19.     }  
  20.   
  21.     char c ;  
  22.     while ((c = getchar()) != ‘q’);  
  23.   
  24.     printf(“Now terminate the thread!\n”);  
  25.     flag = 0;  
  26.     printf(“Wait for thread to exit\n”);  
  27.     pthread_join(thread, NULL);  
  28.     printf(“Bye\n”);  
  29.     return 0;  
  30. }  

输入q后,需要等线程从sleep中醒来(由挂起状态变为运行状态),即最坏情况要等10s,线程才会被join。采用sleep的缺点:不能及时唤醒线程。
采用pthread_cond_timedwait函数实现的如下

  1. include <stdio.h>  
  2. include <sys/time.h>  
  3. include <unistd.h>  
  4. include <pthread.h>  
  5. include <errno.h>  
  6.   
  7. pthread_t thread;  
  8. pthread_cond_t cond;  
  9. pthread_mutex_t mutex;  
  10. unsigned char flag = 1;  
  11.   
  12. void * thr_fn(void * arg)  
  13. {  
  14.     struct timeval now;  
  15.     struct timespec outtime;  
  16.     pthread_mutex_lock(&mutex);  
  17.     while (flag)  
  18.     {  
  19.         printf(“thread sleep now\n”);  
  20.         gettimeofday(&now, NULL);  
  21.         outtime.tv_sec = now.tv_sec + 10;  
  22.         outtime.tv_nsec = now.tv_usec * 1000;  
  23.         pthread_cond_timedwait(&cond, &mutex, &outtime);  
  24.     }  
  25.     pthread_mutex_unlock(&mutex);  
  26.     printf(“thread exit\n”);  
  27. }  
  28.   
  29. int main()  
  30. {  
  31.     char c ;  
  32.     pthread_mutex_init(&mutex, NULL);  
  33.     pthread_cond_init(&cond, NULL);  
  34.     if (0 != pthread_create(&thread, NULL, thr_fn, NULL))  
  35.     {  
  36.         printf(“error when create pthread,%d\n”, errno);  
  37.         return 1;  
  38.     }  
  39.       
  40.     while ((c = getchar()) != ‘q’);  
  41.     printf(“Now terminate the thread!\n”);  
  42.     flag = 0;  
  43.     pthread_mutex_lock(&mutex);  
  44.     pthread_cond_signal(&cond);  
  45.     pthread_mutex_unlock(&mutex);  
  46.     printf(“Wait for thread to exit\n”);  
  47.     pthread_join(thread, NULL);  
  48.     printf(“Bye\n”);  
  49.     return 0;  
  50. }  

条件变量是 GNU/Linux 提供的第三种同步工具(第一互斥体第二这信号量);利用它你可以在多线程环境下实现更复杂的条件控制。

    当标志没有被设置的时候,线程会不断循环检测这个标志同时会不断锁定、解锁互斥体,浪费 CPU  时间。你真正需要的是这样一种方法:当标志没有设置的时候让线程进入休眠状态;而当某种特定条件出现时,标志位被设置,线程被唤醒。

    如同信号量,线程可以对一个条件变量执行等待操作。如果如果线程 A 正在等待一个条件变量,它会被阻塞直到另外一个线程B,向同一个条件变量发送信号以改变其状态。不同于信号量,条件变量没有计数值,也不占据内存空间,线程 A 必须在 B 发送信号之前开始等待。如果 B 在 A 执行等待操作之前发送了信号,这个信号就丢失了,同时 A会一直阻塞直到其它线程再次发送信号到这个条件变量。

    条件变量将允许你实现这样的目的:在一种情况下令线程继续运行,而相反情况下令线程阻塞。只要每个可能涉及到改变状态的线程正确使用条件变量,linux 将保证当条件改变的时候由于一个条件变量的状态被阻塞的线程均能够被激活。

     GNU/Linux 刚好提供了这个机制,每个条件变量都必须与一个互斥体共同使用,以防止这种竞争状态的发生。这种设计下,线程函数应遵循以下步骤: 

  1.  thread_function中的循环首先锁定互斥体并且读取标志变量的值。 
  2.   如果标志变量已经被设定,该线程将互斥体解锁然后执行工作函数
  3.   如果标志没有被设置,该线程自动锁定互斥体并开始等待条件变量的信号

     这里最关键的特点就在第三条。这里,GNU/Linux系统允许你用一个原子操作完成解除互斥体锁定和等待条件变量信号的过程而不会被其它线程在中途插入执行。这就避免了在thread_function中检测标志和等待条件变量的过程中其它线程修改标志变量并对条件变量发送信号的可能性。

   pthread_cond_t  pCond;

   pthread_cond_init(&pCond,NULL); 第一个参数是一个指向pthread_cond_t变量的指针。第二个参数是一个指向条件变量属性对象的指针;这个参数在 GNU/Linux 系统中是被忽略的。

    pthread_cond_signal(&pCond)如果没有线程正在等待这个信号,则这个信号会被忽略。该函数的
参数是一个指向 pthread_cond_t 类型变量的指针。
    pthread_cond_broadcast()函数会将所有等待该条件变量的线程解锁而不是仅仅解锁一个线程         

    pthread_cond_wait(&pCond,&mutex)会让调用线程阻塞直到条件变量收到信号。第一个参数是指向一个 pthread_cond_t 类型变量的指针,第二个参数是指向一个pthread_mutex_t类型变量的指针。当调用 pthread_cond_wait 的时候,互斥体对象必须已经被调用线程锁定。这个函数以一个原子操作解锁互斥体并锁定条件变量等待信号。当信号到达且调用线程被解锁之后,pthread_cond_wait自动申请锁定互斥体对象。

 

 
    pthread_mutex_lock(&qlock);  
    pthread_cond_wait(&qready, &qlock);  //其它线程pthread_cond_sigal发出信号才会对出阻塞
    pthread_mutex_unlock(&qlock);

The mutex passed to pthread_cond_wait protects the condition.The caller  passes it locked to the function, which then atomically places the calling thread on the list of threads waiting for thecondition and unlocks the mutex. This closes the window between the time that the  condition is checked and the time that the thread goes to sleep waiting for the condition to change, so that the thread doesn't miss a change in the condition. When pthread_cond_wait returns, the mutex is again locked.
上面是APUE的原话,就是说pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t*mutex)

函数传入的参数mutex用于保护条件,因为我们在调用pthread_cond_wait时,如果条件不成立我们就进入阻塞,但是进入阻塞这个期间,如果条件变量改变了的话,那我们就漏掉了这个条件。因为这个线程还没有放到等待队列上,所以调用pthread_cond_wait前要先锁互斥量,即调用pthread_mutex_lock(),pthread_cond_wait在把线程放进阻塞队列后,自动对mutex进行解锁,使得其它线程可以获得加锁的权利。这样其它线程才能对临界资源进行访问并在适当的时候唤醒这个阻塞的进程。当pthread_cond_wait返回的时候又自动给mutex加锁
实际上边代码的加解锁过程如下:

pthread_mutex_lock(&qlock);   
pthread_cond_wait(&qready, &qlock);
pthread_mutex_unlock(&qlock);

### 回答1: pthread_cond_broadcast 是一个线程同步的函数,用于广播通知一个条件变量的等待队列中的所有线程,使它们都被唤醒并开始执行。在多线程编程中,pthread_cond_broadcast 可以和 pthread_cond_wait 一起使用,实现线程的等待和唤醒,从而实现线程间的同步。当某个条件变量的状态发生变化时,调用 pthread_cond_broadcast 可以通知所有正在等待该条件变量的线程,让它们重新争抢锁并执行。 ### 回答2: pthread_cond_broadcast是一个线程库函数,用于向等待在某个条件变量上的所有线程发送信号,以通知它们条件已经满足,可以继续执行。 调用pthread_cond_broadcast函数时,会将条件变量相关联的所有线程同时唤醒。但需要注意的是,被唤醒的线程不会立即执行,而是等待获取到互斥锁后再开始执行。 使用pthread_cond_broadcast函数的典型场景是,当某个条件被满足时,需要通知所有等待该条件的线程,以便它们可以执行相关的操作。例如,一个生产者线程向缓冲区中放入数据,当缓冲区满时,其他等待该条件的消费者线程需要被及时唤醒,以便消费数据。 当调用pthread_cond_broadcast时,需要保证对应的互斥锁已经被锁定,不然会产生未定义的行为。因此,在调用过程中,通常需要与pthread_mutex_lock配合使用来确保线程安全。 总之,pthread_cond_broadcast函数能够向等待在条件变量上的所有线程发送信号,并唤醒它们继续执行。它是实现线程间同步和互斥的重要手段之一,可以提高多线程程序的效率和性能。 ### 回答3: pthread_cond_broadcast是一个函数,用于发送信号给正在等待条件变量的所有线程。当条件变量的状态发生变化时,调用pthread_cond_broadcast函数可以通知等待该条件变量的所有线程继续执行。 pthread_cond_broadcast函数的调用会唤醒所有等待该条件变量的线程,使它们从等待状态变为可运行状态,以便在调度器的调度下参与到运行中的线程队列中。 使用pthread_cond_broadcast的过程一般需要和pthread_mutex结合使用。在等待条件变量之前,需要先使用pthread_mutex_lock对互斥锁进行加锁,以确保在调用pthread_cond_broadcast函数时,条件变量不会被其他线程改变。然后使用pthread_cond_wait等待条件变量的变化,当需要唤醒等待线程时,再使用pthread_cond_broadcast发送信号。最后释放互斥锁,再继续执行其他操作。 当调用pthread_cond_broadcast函数时,所有等待该条件变量的线程都会被唤醒,但具体唤醒的顺序是不确定的。唤醒后的线程会再次竞争互斥锁,只有获得互斥锁的线程才能继续执行。其他未获得互斥锁的线程需要再次等待条件变量的唤醒。 这种线程之间的同步机制可以有效地保证线程按照规定的顺序执行,避免竞争和冲突的问题。pthread_cond_broadcast的使用可以更好地利用多核系统的计算能力,提高线程的并行执行效率。同时,通过合理地使用互斥锁和条件变量,还可以防止线程的饥饿和死锁问题的发生,保障程序的正常运行。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值