POSIX条件变量---以生产者、消费者为实例

条件变量(Condition Variables)

条件变量是什么?

  • 条件变量为我们提供了另一种线程间同步的方法,然而,互斥量是通过控制线程访问数据来实现同步,条件变量允许线程同步是基于实际数据的值。
  • 如果没有条件变量,程序员需要让线程不断地轮询,以检查是否满足条件。由于线程处在一个不间断的忙碌状态,所以这是相当耗资源的。条件变量就是这么一个不需要轮询就可以解决这个问题的方法。
  • 条件变量总是跟互斥锁(mutex lock)一起使用。
  • 下面是使用条件变量的比较典型的过程:

主线程

  • 声明并初始化需要同步的全局数据或变量(例如”count“)
  • 声明并初始化一个条件变量对象
  • 声明并初始化一个与条件变量关联的互斥量
  • 创建线程A和B并开始运行

线程A

  • 线程运转至某一个条件被触发(例如,”count“必须达到某个值)
  • 锁定相关联的互斥量并检查全局变量的值
  • 调用pthread_con_wait()阻塞线程等待线程B的信号。请注意,调用pthread_con_wait()以自动的原子方式(atomically)解锁相关联的互斥量,以便于可以被线程B使用。
  • 当收到信号时,唤醒线程。互斥量被以自动的原子方式被锁定。
  • 明确的解锁互斥量。
  • 继续

线程 B

  • 线程运转
  • 锁定相关联的互斥量
  • 更改线程A正在等待的全局变量的值
  • 检查线程A等待的变量值,如果满足条件,发信号给线程A
  • 解锁互斥量
  • 继续

主线程

  • Join / Continue

       与互斥锁不同,条件变量是用来等待而不是用来上锁的。条件变量用来自动阻塞调用线程, 直到条件变量所要求的情况发生为止。通常条件变量需要和互斥锁同时使用, 利用互斥量保护条件变量;

       条件的检测是在互斥锁的保护下进行的。如果一个条件为假,一个线程自动阻塞,并释放等待状态改变的互斥锁。如果另一个线程改变了条件,它就发送信号给关联的条件变量, 并唤醒一个或多个等待在该条件变量上的线程,这些线程将重新获得互斥锁,重新评价条件。如果将条件变量放到共享内存中, 而两进程可共享读写这段内存,则条件变量可以被用来实现两进程间的线程同步。

       

条件变量API说明

int pthread_cond_init(pthread_cond_t *cond, pthread_condattr_t *cond_attr);
int pthread_cond_destroy(pthread_cond_t *cond);
 
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);
 
int pthread_cond_signal(pthread_cond_t *cond);
int pthread_cond_broadcast(pthread_cond_t *cond);

1.pthread_cond_init

使用条件变量之前要先进行初始化:可以在单个语句中生成和初始化一个条件变量如:

  pthread_cond_t my_condition=PTHREAD_COND_INITIALIZER; //用于进程间线程的通信;

  或用函数pthread_cond_init进行动态初始化;

 

2.pthread_cond_destroy

该函数可以用来摧毁所指定的条件变量,同时将会释放所给它分配的资源。调用该函数的进程并不要求等待在参数所指定的条件变量上;

 

3.pthread_cond_wait && pthread_cond_timedwait

cond_wait原语完成三件事:

  (1)对mutex解锁;

  (2)等待条件, 直到有线程向他发送通知;

  (3)当wait返回时, 再对mutex重新加锁;

第一个参数cond是指向一个条件变量的指针。第二个参数mutex则是对相关的互斥锁的指针。

函数pthread_cond_timedwait函数类型与函数pthread_cond_wait区别在于:timedwait多了一个超时, 超时值制订了我们愿意等待多长时间, 如果达到或是超过所引用的参数*abstime,它将结束阻塞并返回错误ETIME.

//timespec结构如下:

struct timespec

{

time_t tv_sec; /* seconds */

long tv_nsec; /* nanoseconds */

};

注意: 这个时间值是一个绝对数而不是相对数, 例如, 假设愿意等待三秒钟, 那么并不是把3秒钟转换成timespec结构, 而是需要将当前实践加上3分钟再转换成timespec结构, 这个获取当前时间值的函数可以是clock_gettime(我们采用这一个)也可以是gettimeofday.

4.pthread_cond_signal && pthread_cond_broadcast

cond_signal原语所完成的操作:

  向第一个等待条件的线程发起通知, 如果没有任何一个线程处于等待条件的状态, 那么这个通知将被忽略;

cond_broadcast:

  向所有等待在该条件上的线程发送通知;

参数cond是一个条件变量的指针。当调用signal时, 一个在相同条件变量上阻塞的线程将被解锁。如果同时有多个线程阻塞,则由调度策略确定接收通知的线程。如果调用broadcast,则将通知阻塞在这个条件变量上的所有线程。一旦被唤醒,线程仍然会要求互斥锁。如果当前没有线程等待通知,则上面两种调用实际上成为一个空操作, 内核会将条件变量的通知忽略(如果参数*cond指向非法地址,则返回值EINVAL);

条件变量使用规范

1.等待条件代码

pthread_mutex_lock(&mutex);

while (条件为假)

{

pthread_cond_wait(&cond, &mutex);

}

修改条件

pthread_mutex_unlock(&mutex);

/**

解释: 为什么使用while, 而不用if?

Man-Page给出了答案: If a signal is delivered to a thread waiting for a condition variable, upon return from 

the signal handler the thread resumes waiting for the condition variable as if it was not interrupted, or 

it shall return zero due to spurious wakeup.

即是说如果正在等待条件变量的一个线程收到一个信号,从信号处理函数返回的时候线程应该重新等待条件变量就好象没有被中断一样,或者被虚假地唤醒返回0。如果是上述情形,那么其实条件并未被改变,那么此时如果没有继续判断一下条件的真假就继续向下执行的话,修改条件将会出现问题,所以需要使用while 循环再判断一下,如果条件还是为假必须继续等待。

(因为pthread_cond_wait会 被虚假唤醒,然而条件变量却没有改变,所以用while可以再次判定条件变量)

注:在多处理器系统中,pthread_cond_signal 可能会唤醒多个等待条件的线程,这也是一种spurious wakeup。

**/

2.给条件发送信号代码

pthread_mutex_lock(&mutex);

设置条件为真

pthread_cond_signal(&cond);

pthread_mutex_unlock(&mutex);
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
 
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <pthread.h>
 
#define ERR_EXIT(m)\
	do \
	{ \
		perror(m); \
		exit(EXIT_FAILURE); \
	}while(0)
 
 
#define CONSUMERS_COUNT 2
#define PRODUCERS_COUNT 1
 
pthread_mutex_t g_mutex;
pthread_cond_t g_cont;
 
int iread;
 
pthread_t g_thread[CONSUMERS_COUNT+PRODUCERS_COUNT];
 
void* produce(void* arg)
{
	while(1)
	{
		pthread_mutex_lock(&g_mutex);
		iread++;	
		printf("product iread=%d\n",iread);
		pthread_cond_signal(&g_cont);
		printf("produce is produat\n");
		pthread_mutex_unlock(&g_mutex);
		sleep(3);
	}
	return NULL;
}
void* consumer(void* arg)
{
	
	while(1)
	{
	
		pthread_mutex_lock(&g_mutex);
		printf("consumer iread =%d\n",iread);	
		while(iread==0)
		{
			pthread_cond_wait(&g_cont, &g_mutex);
			printf("iread is changed\n");
		}
 
		iread--;
		sleep(1);
		pthread_mutex_unlock(&g_mutex);
	}
	return NULL;
} 
 
int main()
{
	int i;
	pthread_mutex_init(&g_mutex,NULL);
	pthread_cond_init(&g_cont,NULL);
	for(i=0; i< PRODUCERS_COUNT;i++)
	{
		pthread_create(&g_thread[i],NULL,produce,(void*)i);
	}
 
	for(i=0; i< CONSUMERS_COUNT;i++)
	{
		pthread_create(&g_thread[i+ PRODUCERS_COUNT],NULL,consumer,(void*)i);
	}
 
	for(i=0; i< PRODUCERS_COUNT+CONSUMERS_COUNT;i++)
	{
		pthread_join(g_thread[i],NULL);
	}
 
	pthread_mutex_destroy(&g_mutex);
	pthread_cond_destroy(&g_cont);
	return 0;
}

C++下的封装:

//Condition类设计
class Condition
{
public:
    Condition(const pthread_mutexattr_t *mutexAttr = NULL,
              const pthread_condattr_t  *condAttr = NULL);
    ~Condition();
 
    //条件变量函数
    int signal();
    int broadcast();
    int wait();
    int timedwait(int seconds);
 
    //互斥量函数
    int lock();
    int trylock();
    int unlock();
 
private:
    pthread_mutex_t m_mutex;
    pthread_cond_t  m_cond;
};
//Condition类实现
Condition::Condition(const pthread_mutexattr_t *mutexAttr,
                     const pthread_condattr_t  *condAttr)
{
    //初始化互斥量
    pthread_mutex_init(&m_mutex, mutexAttr);
    //初始化条件变量
    pthread_cond_init(&m_cond, condAttr);
}
Condition::~Condition()
{
    //销毁互斥量
    pthread_mutex_destroy(&m_mutex);
    //销毁条件变量
    pthread_cond_destroy(&m_cond);
}
int Condition::signal()
{
    return pthread_cond_signal(&m_cond);
}
int Condition::broadcast()
{
    return pthread_cond_broadcast(&m_cond);
}
int Condition::wait()
{
    return pthread_cond_wait(&m_cond, &m_mutex);
}
int Condition::timedwait(int seconds)
{
    //获取当前时间
    struct timespec abstime;
    clock_gettime(CLOCK_REALTIME, &abstime);
    //将当前时间加上需要等待的秒数, 构成绝对时间值
    abstime.tv_sec += seconds;
    return pthread_cond_timedwait(&m_cond, &m_mutex, &abstime);
}
 
int Condition::lock()
{
    return pthread_mutex_lock(&m_mutex);
}
int Condition::trylock()
{
    return pthread_mutex_trylock(&m_mutex);
}
int Condition::unlock()
{
    return pthread_mutex_unlock(&m_mutex);
}
/** 实现: 我们假设是缓冲区是无界的
说明:生产者可以不停地生产,使用pthread_cond_signal  发出通知的时候,如果此时没有消费者线程在等待条件,那么这个通知将被丢弃,但也不影响整体代码的执行,没有消费者线程在等待,说明产品资源充足,即while 判断失败,不会进入等待状态,直接消费产品(即修改条件)。
**/
const unsigned int PRODUCER_COUNT = 5;	//生产者个数
const unsigned int CONSUMER_COUNT = 3;	//消费者个数
 
//定义Condition类
Condition cond;
//缓冲区 ~O(∩_∩)O~
int nReady = 0;
//消费者
void *consumer(void *args)
{
    int id = *(int *)args;
    delete (int *)args;
    while (true)
    {
        cond.lock();    //锁定mutex
        while (!(nReady > 0))
        {
            printf("-- thread %d wait...\n", id);
            cond.wait();    //等待条件变量
        }
 
        printf("** thread %d alive, and consume product %d ...\n", id, nReady);
        -- nReady;  //消费
        printf("   thread %d end consume... \n\n", id);
 
        cond.unlock();  //解锁mutex
        sleep(1);
    }
    pthread_exit(NULL);
}
 
//生产者
void *producer(void *args)
{
    int id = *(int *)args;
    delete (int *)args;
    while (true)
    {
        cond.lock();    //锁定mutex
 
        printf("++ thread %d signal, and produce product %d ...\n", id, nReady+1);
        ++ nReady;      //生产
        cond.signal();  //发送条件变量信号
        printf("   thread %d end produce, signal...\n\n", id);
        cond.unlock();  //解锁mutex
        sleep(1);
    }
    pthread_exit(NULL);
}
 
int main()
{
    pthread_t thread[PRODUCER_COUNT+CONSUMER_COUNT];
 
    //首先生成消费者
    for (unsigned int i = 0; i < CONSUMER_COUNT; ++i)
        pthread_create(&thread[i], NULL, consumer, new int(i));
    sleep(1);   //使生产者等待一段时间, 加速消费者等待事件产生
    //然后生成生产者
    for (unsigned int i = 0; i < PRODUCER_COUNT; ++i)
        pthread_create(&thread[CONSUMER_COUNT+i], NULL, producer, new int(i));
    for (unsigned int i = 0; i < PRODUCER_COUNT+CONSUMER_COUNT; ++i)
        pthread_join(thread[i], NULL);
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值