pthread_cond_broadcast

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 <pthread.h>

  3. #include <stdlib.h>

  4. #include <time.h>

  5. #include <unistd.h>

  6. #include <string.h>

  7. #include <errno.h>

  8.  
  9. pthread_t thread;

  10. pthread_cond_t cond;

  11. pthread_mutex_t mutex;

  12. unsigned char flag = 1;

  13.  
  14. void * thr_fn(void * arg)

  15. {

  16. int loop = 0;

  17. struct timeval now;

  18. struct timespec outtime;

  19. pthread_mutex_lock(&mutex);

  20. while (flag)

  21. {

  22. printf("thread[%u] sleep now, loop=%d\n", (unsigned int)pthread_self(), loop);

  23. gettimeofday(&now, NULL);

  24. outtime.tv_sec = now.tv_sec + 1;

  25. outtime.tv_nsec = now.tv_usec * 1000;

  26. pthread_cond_timedwait(&cond, &mutex, &outtime);

  27. loop++;

  28. }

  29. pthread_mutex_unlock(&mutex);

  30. printf("[%s,%d], thread[%u] exit\n", __FUNCTION__, __LINE__, (unsigned int)pthread_self());

  31. }

  32.  
  33. int main(int argc, char **argv)

  34. {

  35. char c ;

  36. pthread_mutex_init(&mutex, NULL);

  37. pthread_cond_init(&cond, NULL);

  38. if (0 != pthread_create(&thread, NULL, thr_fn, NULL))

  39. {

  40. printf("error when create pthread,%d\n", errno);

  41. return 1;

  42. }

  43. printf("please input any key to exit thread[%u]\n", (unsigned int)thread);

  44. while (c = getchar() != 'q')

  45. {

  46. printf("Now terminate the thread!\n");

  47. flag = 0;

  48. pthread_mutex_lock(&mutex);

  49. pthread_cond_signal(&cond);

  50. pthread_mutex_unlock(&mutex);

  51. printf("Wait for thread to exit\n");

  52. pthread_join(thread, NULL);

  53. printf("thread[%u] Bye\n", (unsigned int)thread);

  54. return 0;

  55. }

  56. }


 

条件变量是 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);

猜你喜欢

转载自blog.csdn.net/nawenqiang/article/details/81159874