linux生产者消费者(1)

一、条件变量

                  条件变量http://www.cnblogs.com/motadou/archive/2010/02/13/1668075.html

                  生产者消费者http://www.cnblogs.com/justinzhang/archive/2011/12/21/2296289.html

                  条件变量锁问题http://www.cnblogs.com/liulipeng/p/3552767.html

二、示例代码

#include "pthread.h" 
#define BUFFER_SIZE 4 

struct prodcons {
	int buffer[BUFFER_SIZE];
	pthread_mutex_t lock;
	int readpos, writepos;
	pthread_cond_t notempty;
	pthread_cond_t notfull;
 };
  
#define OVER (-1) 
struct prodcons b;
static int n = 1;
 
void *producer(void *data)  
{
	while(1)
    {
		sleep(1);//至少间隔2s才生产一次数据
		pthread_mutex_lock(&b.lock);
		while ((b.writepos + 1) % BUFFER_SIZE == b.readpos)//如果读写的位置相差1,则认为缓冲区满
		{
			printf("wait for not full\n");
			pthread_cond_wait(&b.notfull, &b.lock);//等待缓冲区不满
		}
		printf("producer     create      data[%d] = %d\n",b.writepos,n);
		b.buffer[b.writepos++] = n++; //生产新的数据
		if (b.writepos >= BUFFER_SIZE)
			b.writepos = 0;
		pthread_cond_signal(&b.notempty);//通知消费者有新的数据产生
		pthread_mutex_unlock(&b.lock);
    }
	return NULL;
}
 
void *consumer(void *data)  
{
    int d;
    while (1)
    {
	sleep(((rand()%2)==1)?0:2);//随机睡眠1到3s之间,就会有生产者和消费者之间生产和消费速度不匹配
        pthread_mutex_lock(&b.lock);
		while (b.writepos == b.readpos)//buffer为空
		{
			printf("wait for not empty\n");
			pthread_cond_wait(&b.notempty, &b.lock);//等待buffer不为空
		}
		
		d = b.buffer[b.readpos];//消费者消费数据
		printf("consumer use data[%d] = %d\n",b.readpos,d);
		b.readpos++;
		if (b.readpos >= BUFFER_SIZE)
			b.readpos = 0; 
		pthread_mutex_unlock(&b.lock);  
		pthread_cond_signal(&b.notfull)

     }
     return NULL;
 }
 
int main(void)  
{
	pthread_t th_a, th_b; 
    void *retval; 
	
	pthread_mutex_init(&b.lock, NULL); 
    pthread_cond_init(&b.notempty, NULL);
    pthread_cond_init(&b.notfull, NULL);
    b.readpos = 0;
	b.writepos = 0;
	
    pthread_create(&th_a, NULL, producer, 0);
    pthread_create(&th_b, NULL, consumer, 0);
    pthread_join(th_a, &retval);
    pthread_join(th_b, &retval);
	return 0;
 }

三、效果演示


四、问题思考

 1.为什么使用条件变量需要配合互斥锁?

 2.互斥锁是来保护什么变量的?

你可能感兴趣的:(C语言(基础,Linux,C))