pthread

关于pthread_cond_signal函数(zz)
 

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

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

另外,互斥量的作用一般是用于对某个资源进行互斥性的存取,很多时候是用来保证操作是一个原子性的操作,是不可中断的。

pthread_cond_signal函数与条件变量的典型应用就是用来实现producer/consumer模型。

[code]
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>

#define BUFFER_SIZE 8

struct Products
{
int buffer[BUFFER_SIZE];
pthread_mutex_t locker;           //保证存取操作的原子性 互斥性
pthread_cond_t notEmpty; //是否可读       
pthread_cond_t notFull;          //是否可写
int posReadFrom;
int posWriteTo;
};

int BufferIsFull(struct Products* products)
{
if ((products->posWriteTo + 1) % BUFFER_SIZE == products->posReadFrom)
{
return (1);
}
return (0);
}

int BufferIsEmpty(struct Products* products)
{
if (products->posWriteTo == products->posReadFrom)
{
return (1);
}

return (0);
}

//制造产品。

void Produce(struct Products* products, int item)
{
pthread_mutex_lock(&products->locker); //原子操作

while (BufferIsFull(products))
{
pthread_cond_wait(&products->notFull, &products->locker);
} //无空间可写入

//写入数据
products->buffer[products->posWriteTo] = item;
products->posWriteTo++;

if (products->posWriteTo >= BUFFER_SIZE)
products->posWriteTo = 0;

pthread_cond_signal(&products->notEmpty);     //发信
pthread_mutex_unlock(&products->locker);    //解锁
}

int Consume(struct Products* products)
{
int item;

pthread_mutex_lock(&products->locker);

while (BufferIsEmpty(products))
{
pthread_cond_wait(&products->notEmpty, &products->locker);
} //为空时持续等待,无数据可读

//提取数据
item = products->buffer[products->posReadFrom];
products->posReadFrom++;

if (products->posReadFrom >= BUFFER_SIZE) //如果到末尾,从头读取
products->posReadFrom = 0;

pthread_cond_signal(&products->notFull); 
pthread_mutex_unlock(&products->locker);

return item;
}


#define END_FLAG (-1)

struct Products products;

void* ProducerThread(void* data)
{
int i;
for (i = 0; i < 16; ++i)
{
printf("producer: %d\n", i);
Produce(&products, i);
}
Produce(&products, END_FLAG);
return NULL;
}

void* ConsumerThread(void* data)
{
int item;

while (1)
{
item = Consume(&products);
if (END_FLAG == item)
       break;
printf("consumer: %d\n", item);
}
return (NULL);
}

int main(int argc, char* argv[])
{
pthread_t producer;
pthread_t consumer;
int result;

pthread_create(&producer, NULL, &ProducerThread, NULL);
pthread_create(&consumer, NULL, &ConsumerThread, NULL);

pthread_join(producer, (void *)&result);
pthread_join(consumer, (void *)&result);


exit(EXIT_SUCCESS);
}

posted on 2012-02-24 22:39  一指流砂  阅读(375)  评论(0编辑  收藏  举报

导航