最近学习在网络相关的知识,正好项目用到了线程同步的东东,由于操作系统的东东学的非常烂,就借此机会恶补下。废话不多说了,直接上代码
Linux下源码如下:
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define BUFFER_LENGTH 3
typedef struct RecvBuf
{
char buf[2008];
int length;
};
struct RecvBuf buffer[BUFFER_LENGTH];
int front = 0;// 读缓冲区的索引
int rear = -1; // 写缓冲区的索引
int size = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t empty_cond = PTHREAD_COND_INITIALIZER;
pthread_cond_t full_cond = PTHREAD_COND_INITIALIZER;
void *producer(void *arg);
void *consumer(void *arg);
int main(int argc, char **argv)
{
pthread_t producer_id;
pthread_t consumer_id;
pthread_create(&producer_id, NULL, producer, NULL);
pthread_create(&consumer_id, NULL, consumer, NULL);
while (1)
{
sleep(1);
}
return 0;
}
void *producer(void *arg)
{
pthread_detach(pthread_self());
while (1)
{
sleep(1);//调整Sleep时间,可以修改生产数据的速度
pthread_mutex_lock(&mutex);
if (size == BUFFER_LENGTH) // 如果缓冲区已满,等待; 否则,添加新产品
{
printf("buffer is full. producer is waiting...\n");
pthread_cond_wait(&full_cond, &mutex);
}
//缓冲区往尾端添加一个产品
rear = (rear + 1) % BUFFER_LENGTH;
switch(rear)
{
case 0:
{
strcpy(buffer[rear].buf,"www.google.com.cn");
buffer[rear].length = strlen("www.google.com.cn");
break;
}
case 1:
{
strcpy(buffer[rear].buf,"www.google.com.hk");
buffer[rear].length = strlen("www.google.com.hk");
break;
}
default:
{
strcpy(buffer[rear].buf,"www.google.com.tw");
buffer[rear].length = strlen("www.google.com.tw");
break;
}
}
printf("producer produces the item %d,the length=%d,the buf=%s\n", rear, buffer[rear].length,buffer[rear].buf);
++size;
printf("producer size %d\n", size);
if (size == 1) // 如果当前size=1, 说明以前size=0, 消费者在等待,则给消费者发信号
{
pthread_cond_signal(&empty_cond);
}
pthread_mutex_unlock(&mutex);
}
}
void *consumer(void *arg)
{
pthread_detach(pthread_self());
while (1)
{
sleep(3);
pthread_mutex_lock(&mutex);
printf("consumer size %d\n", size);
if (size == 0) // 如果缓冲区已空,等待; 否则,消费产品
{
printf("buffer is empty. consumer is waiting...\n");
pthread_cond_wait(&empty_cond, &mutex);
}
//从缓冲区中消费一个产品
printf("consumer consumes an item=%d: the length=%d and buf=%s\n", front, buffer[front].length,buffer[front].buf);
front = (front + 1) % BUFFER_LENGTH;
--size;
if (size == BUFFER_LENGTH-1) // 如果当前size=BUFFER_LENGTH-1,说明消费之前生产者在等待,则给生产者发信号
{
pthread_cond_signal(&full_cond);
}
pthread_mutex_unlock(&mutex);
}
}