理解 Linux 条件变量

来源:互联网 发布:c语言程序如何模块化 编辑:程序博客网 时间:2024/05/17 08:38

理解 Linux 条件变量

1 简介

当多个线程之间因为存在某种依赖关系,导致只有当某个条件存在时,才可以执行某个线程,此时条件变量(pthread_cond_t)可以派上用场。比如:

    例1: 当系统不忙(这是一个条件)时,执行扫描文件状态的线程。

    例2: 多个线程组成线程池,只有当任务队列中存在任务时,才用其中一个线程去执行这个任务。为避免惊群(thrundering herd),可以采用条件变量同步线程池中的线程。

2 用法

条件变量(pthread_cond_t)必须与锁(pthread_mutex_t)一起使用。

条件变量的API:

1) pthread_cond_init

2) pthread_cond_signal / pthread_cond_broadcast

3) pthread_cond_wait / pthread_cond_timedwait

4) pthread_cond_destroy


线程A:

[cpp] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. include <stdio.h>    
  2. include <sys/time.h>    
  3. include <unistd.h>    
  4. include <pthread.h>    
  5. include <errno.h>  
  6. ...  
  7.   
  8. void A_thread_run(void *arg)  
  9. {  
  10.     ...  
  11.   
  12.     pthread_mutex_lock (& lock);  
  13.   
  14.     // 条件满足, 发出通知   
  15.     pthread_cond_signal (& cond);  
  16.   
  17.     pthread_mutex_unlock (& lock);  
  18.   
  19.     ...  
  20. }  


线程B:

[cpp] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. void B_thread_run(void *arg)  
  2. {  
  3.     for ( ; ; ) {  
  4.         pthread_mutex_lock (&lock);  
  5.   
  6.         /* pthread_cond_wait 原子调用: 等待条件变量, 解除锁, 然后阻塞 
  7.          * 当 pthread_cond_wait 返回,则条件变量有信号,同时上锁 
  8.          * 
  9.          * 等待条件有两种方式:条件等待pthread_cond_wait()和计时等待pthread_cond_timedwait(), 
  10.          * 其中计时等待方式如果在给定时刻前条件没有满足,则返回ETIMEOUT 
  11.          * 无论哪种等待方式,都必须和一个互斥锁配合,以防止多个线程同时请求pthread_cond_wait() 
  12.          * (或pthread_cond_timedwait(),下同)的竞争条件(Race Condition)。 
  13.          * mutex互斥锁必须是普通锁(PTHREAD_MUTEX_TIMED_NP)或者适应锁(PTHREAD_MUTEX_ADAPTIVE_NP), 
  14.          * 且在调用pthread_cond_wait()前必须由本线程加锁(pthread_mutex_lock()),而在更新条件等待队列以前, 
  15.          * mutex保持锁定状态,并在线程挂起进入等待前解锁。 
  16.          * 在条件满足从而离开pthread_cond_wait()之前,mutex将被重新加锁,以与进入pthread_cond_wait()前的加锁动作对应。 
  17.          * 激发条件有两种形式,pthread_cond_signal()激活一个等待该条件的线程,存在多个等待线程时按入队顺序激活其中一个; 
  18.          * 而pthread_cond_broadcast()则激活所有等待线程(惊群)。 
  19.          */  
  20.   
  21.         pthread_cond_wait (&cond, &lock);  
  22.   
  23.         if (shutdown) {  
  24.             break;  
  25.         }  
  26.   
  27.         /* Unlock */  
  28.         pthread_mutex_unlock (&lock);  
  29.   
  30.         /* do your task here */  
  31.     }  
  32.   
  33.     pthread_mutex_unlock (&lock);  
  34.     pthread_exit (0);  
  35. }  


线程B调用pthread_cond_wait,从而阻塞在此句,等待有信号通知。pthread_cond_wait内部存在原子调用:解除锁和等待条件变量有信号。当pthread_cond_wait函数返回,表明得到了信号通知,同时上锁。

线程A用pthread_cond_signal通知调用了pthread_cond_wait的线程B

3 避免惊群

这是个狼多肉少,僧多粥少,色鬼多美女少的时代。每当一块肉丢到狼群,就引发一群狼去争抢,但最后只有一只狼得到了肉。这就是惊群(thrundering herd)。现实世界的惊群,比如老师在课堂上每次提出一个问题,最后只找一个学生回答,时间久了,学生对这个老师的问题就倦怠了。计算机的惊群会造成服务器资源空耗。

pthread_cond_signal函数的作用是发送一个信号给另外一个正在处于阻塞等待状态的线程,使其脱离阻塞状态,继续执行.如果没有线程处在阻塞等待状态,pthread_cond_signal也会成功返回。

但使用pthread_cond_signal不会有“惊群现象”产生,它最多只给一个线程发信号。假如有多个线程正在阻塞等待着这个条件变量的话,那么是根据各等待线程优先级的高低确定哪个线程接收到信号开始继续执行。如果各线程优先级相同,则根据等待时间的长短来确定哪个线程获得信号。但无论如何一个pthread_cond_signal调用最多发信一次。

4 线程池threadpool

经典的例子就是一个线程池是一个固定数目的线程的组合,其中每个线程(worker)完全可以做相同的工作。线程池包含这样一个任务(task)队列,用户向任务队列中添加任务,线程池自动派发线程去执行任务。

每个线程有特定于线程的参数(thread argument),每个任务也有特定于任务的数据(task argument)。线程函数执行任务函数,同时传递给任务函数线程参数和任务参数。

典型的例子就是每个线程包含了到数据库或其他资源的连接,任务函数可以安全地使用这些连接,因为任务函数是在线程函数中同步执行的。

下面是完整的线程池代码,原来的代码中没有特定于线程的参数,我添加了这部分代码。

threadpool.h

[cpp] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. /* 
  2.  * 2014-06-18: last modified by cheungmine 
  3.  * 
  4.  * Copyright (c) 2011, Mathias Brossard <mathias@brossard.org>. 
  5.  * All rights reserved. 
  6.  *  
  7.  * Redistribution and use in source and binary forms, with or without 
  8.  * modification, are permitted provided that the following conditions are 
  9.  * met: 
  10.  *  
  11.  *  1. Redistributions of source code must retain the above copyright 
  12.  *     notice, this list of conditions and the following disclaimer. 
  13.  *  
  14.  *  2. Redistributions in binary form must reproduce the above copyright 
  15.  *     notice, this list of conditions and the following disclaimer in the 
  16.  *     documentation and/or other materials provided with the distribution. 
  17.  *  
  18.  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
  19.  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
  20.  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 
  21.  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
  22.  * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
  23.  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 
  24.  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 
  25.  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 
  26.  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
  27.  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 
  28.  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
  29.  */  
  30.   
  31. #ifndef _THREADPOOL_H_   
  32. #define _THREADPOOL_H_   
  33.   
  34. #ifndef POOL_MAX_THREADS   
  35. #   define POOL_MAX_THREADS  256  
  36. #endif   
  37.   
  38. #ifndef POOL_MAX_QUEUES   
  39. #   define POOL_MAX_QUEUES  1024  
  40. #endif   
  41.   
  42. #ifndef POOL_DEFAULT_THREADS   
  43. #   define POOL_DEFAULT_THREADS  32  
  44. #endif   
  45.   
  46. #ifndef POOL_DEFAULT_QUEUES   
  47. #   define POOL_DEFAULT_QUEUES  256  
  48. #endif   
  49.   
  50. /** 
  51.  * @file threadpool.h 
  52.  * @brief Threadpool Header file 
  53.  */  
  54.   
  55. typedef struct threadpool_t threadpool_t;  
  56.   
  57. /** 
  58.  * @file threadpool.h 
  59.  * @brief thread_context_t 
  60.  *   thread can take itself argument 
  61.  *   added by cheungmine. 
  62.  *   2014-06-17 
  63.  */  
  64. typedef struct thread_context_t  
  65. {  
  66.     void *pool;  
  67.     pthread_t thread;  
  68.     void *thread_arg;  
  69.     struct threadpool_task_t *task;  
  70. } thread_context_t;  
  71.   
  72. /** 
  73.  *  @struct threadpool_task 
  74.  *  @brief the work struct 
  75.  * 
  76.  *  @var function Pointer to the function that will perform the task. 
  77.  *  @var argument Argument to be passed to the function. 
  78.  */  
  79. typedef struct threadpool_task_t  
  80. {  
  81.     void (*function)(thread_context_t *);  
  82.     int    flags;     /* user defined */  
  83.     void * argument;  
  84. } threadpool_task_t;  
  85.   
  86.   
  87. typedef enum  
  88. {  
  89.     threadpool_invalid        = -1,  
  90.     threadpool_lock_failure   = -2,  
  91.     threadpool_queue_full     = -3,  
  92.     threadpool_shutdown       = -4,  
  93.     threadpool_run_failure    = -5,  
  94.     threadpool_out_memory     = -6  
  95. } threadpool_error_t;  
  96.   
  97. static const char* threadpool_error_messages[] = {  
  98.     "threadpool_success",  
  99.     "threadpool_invalid",  
  100.     "threadpool_lock_failure",  
  101.     "threadpool_queue_full",  
  102.     "threadpool_shutdown",  
  103.     "threadpool_run_failure",  
  104.     "threadpool_out_memory"  
  105. };  
  106.   
  107. /** 
  108.  * @function threadpool_create 
  109.  * @brief Creates a threadpool_t object. 
  110.  * @param thread_count Number of worker threads. 
  111.  * @param queue_size   Size of the queue. 
  112.  * @param thread_args  array of arguments with count of thread_count, NULL if ignored. 
  113.  * @param flags        Unused parameter. 
  114.  * @return a newly created thread pool or NULL 
  115.  */  
  116. threadpool_t *threadpool_create (int thread_count, int queue_size, void **thread_args, int flags);  
  117.   
  118. /** 
  119.  * @function threadpool_add 
  120.  * @brief add a new task in the queue of a thread pool 
  121.  * @param pool     Thread pool to which add the task. 
  122.  * @param function Pointer to the function that will perform the task. 
  123.  * @param argument Argument to be passed to the function. 
  124.  * @param flags    Unused parameter. 
  125.  * @return 0 if all goes well, negative values in case of error (@see 
  126.  * threadpool_error_t for codes). 
  127.  */  
  128. int threadpool_add (threadpool_t *pool, void (*routine)(thread_context_t *), void *task_arg, int flags);  
  129.   
  130. /** 
  131.  * @function threadpool_destroy 
  132.  * @brief Stops and destroys a thread pool. 
  133.  * @param pool  Thread pool to destroy. 
  134.  * @param flags Unused parameter. 
  135.  */  
  136. int threadpool_destroy (threadpool_t *pool, int flags);  
  137.   
  138. #endif /* _THREADPOOL_H_ */  

threadpool.c

[cpp] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. /* 
  2.  * 2014-06-18: last modified by cheungmine 
  3.  * 
  4.  * Copyright (c) 2011, Mathias Brossard <mathias@brossard.org>. 
  5.  * All rights reserved. 
  6.  * 
  7.  * Redistribution and use in source and binary forms, with or without 
  8.  * modification, are permitted provided that the following conditions are 
  9.  * met: 
  10.  * 
  11.  *  1. Redistributions of source code must retain the above copyright 
  12.  *     notice, this list of conditions and the following disclaimer. 
  13.  * 
  14.  *  2. Redistributions in binary form must reproduce the above copyright 
  15.  *     notice, this list of conditions and the following disclaimer in the 
  16.  *     documentation and/or other materials provided with the distribution. 
  17.  * 
  18.  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
  19.  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
  20.  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 
  21.  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
  22.  * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
  23.  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 
  24.  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 
  25.  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 
  26.  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
  27.  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 
  28.  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
  29.  */  
  30.   
  31. /** 
  32.  * @file threadpool.c 
  33.  * @brief Threadpool implementation file 
  34.  */  
  35.   
  36. #include <stdlib.h>   
  37. #include <pthread.h>   
  38. #include <unistd.h>   
  39.   
  40. #include "threadpool.h"   
  41.   
  42.   
  43. /** 
  44.  *  @struct threadpool 
  45.  *  @brief The threadpool struct 
  46.  * 
  47.  *  @var notify       Condition variable to notify worker threads. 
  48.  *  @var threads      Array containing worker threads ID. 
  49.  *  @var thread_count Number of threads 
  50.  *  @var queue        Array containing the task queue. 
  51.  *  @var queue_size   Size of the task queue. 
  52.  *  @var head         Index of the first element. 
  53.  *  @var tail         Index of the next element. 
  54.  *  @var shutdown     Flag indicating if the pool is shutting down 
  55.  */  
  56. struct threadpool_t {  
  57.     pthread_mutex_t lock;  
  58.     pthread_cond_t notify;  
  59.   
  60.     int head;  
  61.     int tail;  
  62.     int count;  
  63.     int shutdown;  
  64.     int started;  
  65.   
  66.     int thread_count;  
  67.     int queue_size;  
  68.   
  69.     threadpool_task_t *queues;  
  70.     thread_context_t thread_ctxs[0];  
  71. };  
  72.   
  73. /** 
  74.  * @function void *threadpool_run(void *threadpool) 
  75.  * @brief the worker thread 
  76.  * @param threadpool the pool which own the thread 
  77.  */  
  78. static void *threadpool_run (void *threadpool);  
  79.   
  80. int threadpool_free(threadpool_t *pool);  
  81.   
  82. threadpool_t *threadpool_create(int thread_count, int queue_size, void **thread_args, int flags)  
  83. {  
  84.     int i;  
  85.     threadpool_t *pool = NULL;  
  86.   
  87.     /* Check thread_count for negative or otherwise very big input parameters */  
  88.     if (thread_count < 0 || thread_count > POOL_MAX_THREADS) {  
  89.         goto err;  
  90.     }  
  91.     if (thread_count == 0) {  
  92.         thread_count = POOL_DEFAULT_THREADS;  
  93.     }  
  94.   
  95.     /* Check queue_size for negative or otherwise very big input parameters */  
  96.     if (queue_size < 0 || queue_size > POOL_MAX_QUEUES) {  
  97.         goto err;  
  98.     }  
  99.     if (queue_size == 0) {  
  100.         queue_size = POOL_DEFAULT_QUEUES;  
  101.     }  
  102.   
  103.     /* create threadpool */  
  104.     if ( (pool = (threadpool_t *) malloc (sizeof(threadpool_t) +  
  105.         sizeof(thread_context_t) * thread_count +  
  106.         sizeof(threadpool_task_t) * queue_size)) == NULL ) {  
  107.         goto err;  
  108.     }  
  109.   
  110.     /* Initialize */  
  111.     pool->thread_count = thread_count;  
  112.     pool->queue_size = queue_size;  
  113.     pool->head = pool->tail = pool->count = 0;  
  114.     pool->shutdown = pool->started = 0;  
  115.     pool->queues = (threadpool_task_t *) (& pool->thread_ctxs[thread_count]);  
  116.   
  117.     /* Initialize mutex and conditional variable first */  
  118.     if ((pthread_mutex_init (&(pool->lock), NULL) != 0) ||  
  119.        (pthread_cond_init (&(pool->notify), NULL) != 0)) {  
  120.         goto err;  
  121.     }  
  122.   
  123.     /* Start worker threads */  
  124.     for (i = 0; i < thread_count; i++) {  
  125.         thread_context_t * pctx = & pool->thread_ctxs[i];  
  126.   
  127.         /* set pool to each thread context */  
  128.         pctx->pool = (void*) pool;  
  129.   
  130.         /* assign thread argument if valid */  
  131.         if (thread_args) {  
  132.             pctx->thread_arg = thread_args[i];  
  133.         } else {  
  134.             pctx->thread_arg = 0;  
  135.         }  
  136.   
  137.         if ( pthread_create (& pctx->thread, NULL, threadpool_run, (void*) pctx) != 0) {  
  138.             threadpool_destroy (pool, 0);  
  139.             return NULL;  
  140.         } else {  
  141.             pool->started++;  
  142.         }  
  143.     }  
  144.   
  145.     return pool;  
  146.   
  147.  err:  
  148.     if(pool) {  
  149.         threadpool_free(pool);  
  150.     }  
  151.     return NULL;  
  152. }  
  153.   
  154. int threadpool_add (threadpool_t *pool, void (*function)(thread_context_t *), void *task_arg, int flags)  
  155. {  
  156.     int err = 0;  
  157.     int next;  
  158.   
  159.     if ( pool == NULL || function == NULL ) {  
  160.         return threadpool_invalid;  
  161.     }  
  162.   
  163.     if (pthread_mutex_lock (&(pool->lock)) != 0) {  
  164.         return threadpool_lock_failure;  
  165.     }  
  166.   
  167.     next = pool->tail + 1;  
  168.     next = (next == pool->queue_size) ? 0 : next;  
  169.   
  170.     do {  
  171.         /* Are we full ? */  
  172.         if (pool->count == pool->queue_size) {  
  173.             err = threadpool_queue_full;  
  174.             break;  
  175.         }  
  176.   
  177.         /* Are we shutting down ? */  
  178.         if (pool->shutdown) {  
  179.             err = threadpool_shutdown;  
  180.             break;  
  181.         }  
  182.   
  183.         /* Add task to queue */  
  184.         pool->queues[pool->tail].function = function;  
  185.         pool->queues[pool->tail].argument = task_arg;  
  186.         pool->queues[pool->tail].flags = flags;  
  187.   
  188.         pool->tail = next;  
  189.         pool->count += 1;  
  190.   
  191.         /* pthread_cond_broadcast */  
  192.         if (pthread_cond_signal (&(pool->notify)) != 0) {  
  193.             err = threadpool_lock_failure;  
  194.             break;  
  195.         }  
  196.     } while(0);  
  197.   
  198.     if (pthread_mutex_unlock (&pool->lock) != 0) {  
  199.         err = threadpool_lock_failure;  
  200.     }  
  201.   
  202.     return err;  
  203. }  
  204.   
  205. int threadpool_destroy (threadpool_t *pool, int flags)  
  206. {  
  207.     int i, err = 0;  
  208.   
  209.     if (pool == NULL) {  
  210.         return threadpool_invalid;  
  211.     }  
  212.   
  213.     if (pthread_mutex_lock (&(pool->lock)) != 0) {  
  214.         return threadpool_lock_failure;  
  215.     }  
  216.   
  217.     do {  
  218.         /* Already shutting down */  
  219.         if (pool->shutdown) {  
  220.             err = threadpool_shutdown;  
  221.             break;  
  222.         }  
  223.   
  224.         pool->shutdown = 1;  
  225.   
  226.         /* Wake up all worker threads */  
  227.         if ((pthread_cond_broadcast(&(pool->notify)) != 0) ||  
  228.            (pthread_mutex_unlock(&(pool->lock)) != 0)) {  
  229.             err = threadpool_lock_failure;  
  230.             break;  
  231.         }  
  232.   
  233.         /* Join all worker thread */  
  234.         for (i = 0; i < pool->thread_count; i++) {  
  235.             if (pthread_join (pool->thread_ctxs[i].thread, NULL) != 0) {  
  236.                 err = threadpool_run_failure;  
  237.             }  
  238.         }  
  239.     } while(0);  
  240.   
  241.     if (pthread_mutex_unlock (&pool->lock) != 0) {  
  242.         err = threadpool_lock_failure;  
  243.     }  
  244.   
  245.     /* Only if everything went well do we deallocate the pool */  
  246.     if (!err) {  
  247.         threadpool_free (pool);  
  248.     }  
  249.     return err;  
  250. }  
  251.   
  252. int threadpool_free (threadpool_t *pool)  
  253. {  
  254.     if (pool == NULL || pool->started > 0) {  
  255.         return -1;  
  256.     }  
  257.   
  258.     pthread_mutex_lock (&(pool->lock));  
  259.     pthread_mutex_destroy (&(pool->lock));  
  260.     pthread_cond_destroy (&(pool->notify));  
  261.   
  262.     free(pool);  
  263.     return 0;  
  264. }  
  265.   
  266. /** 
  267.  * each thread run function 
  268.  */  
  269. static void *threadpool_run (void * param)  
  270. {  
  271.     threadpool_task_t task;  
  272.   
  273.     thread_context_t * thread_ctx = (thread_context_t *) param;  
  274.     threadpool_t * pool = thread_ctx->pool;  
  275.   
  276.     for ( ; ; ) {  
  277.         /* Lock must be taken to wait on conditional variable */  
  278.         pthread_mutex_lock (&(pool->lock));  
  279.   
  280.         /* Wait on condition variable, check for spurious wakeups. 
  281.            When returning from pthread_cond_wait(), we own the lock. */  
  282.         while ((pool->count == 0) && (!pool->shutdown)) {  
  283.             pthread_cond_wait (&(pool->notify), &(pool->lock));  
  284.         }  
  285.   
  286.         if (pool->shutdown) {  
  287.             break;  
  288.         }  
  289.   
  290.         /* Grab our task */  
  291.         task.function = pool->queues[pool->head].function;  
  292.         task.argument = pool->queues[pool->head].argument;  
  293.         task.flags    = pool->queues[pool->head].flags;  
  294.   
  295.         thread_ctx->task = &task;  
  296.   
  297.         pool->head += 1;  
  298.         pool->head = (pool->head == pool->queue_size) ? 0 : pool->head;  
  299.         pool->count -= 1;  
  300.   
  301.         /* Unlock */  
  302.         pthread_mutex_unlock (&(pool->lock));  
  303.   
  304.         /* Get to work */  
  305.         (*(task.function)) (thread_ctx);  
  306.     }  
  307.   
  308.     pool->started--;  
  309.   
  310.     pthread_mutex_unlock (&(pool->lock));  
  311.     pthread_exit (NULL);  
  312.     return (NULL);  
  313. }  



0 0