使用Linux线程同步机制解决互斥和同步问题。
问题描述:一组生产者向一组消费者提供消息,它们共享一个有界缓冲池,生产者向其中投放消息,消费者从中取得消息。假定这些生产者和消费者互相等效,只要缓冲池未满,生产者可将消息送入缓冲池;只要缓冲池未空,消费者可从缓冲池取走一个消息。
功能要求:根据进程同步机制,编写一个解决上述问题的程序,可显示缓冲池状态、放数据、取数据等过程。
有2个生产者线程,分别为P1、P2;有2个消费者进程,分别是C1、C2;缓冲区单元个数N=15;
不同的生产者可生产不同的产品(比如字母、数字、符号);不同的消费者可有不同的消费方式(比如“显示”、“打印”、“拼接成字符串”、“改变大小写”等)。自己可任意定义。
使用Linux线程同步:mutex、condition virable和semaphore完成上述问题。
源代码:
#include <pthread.h>
#include <stdio.h>
#include <semaphore.h>
#define NUM 15
int queue[NUM]; static int p = 0,c=0;
sem_t blank_number, product_number;
pthread_mutex_t lock=PTHREAD_MUTEX_INITIALIZER;//实现对queue[NUM]的互斥访问
void *producer1(void *arg) //生产A-Z的大写字母
{ int i=1;
while(i<=5)
{ srand(time(NULL));char ch = 'A' + rand()%25;//一个0到25的随机数加在字符A上就可以得到A到Z之间的一个随机字符
sem_wait(&blank_number); pthread_mutex_lock(&lock);queue[p] = ch;printf("Produce1 %c/n", queue[p]);printf("生产A-Z的大写字母,放入缓冲区中 /n");
p = (p+1)%NUM;pthread_mutex_unlock(&lock);sleep(rand()%5);
sem_post(&product_number); i++;}}
void *producer2(void *arg) //生产100-1000以内的随机数
{ int i=1;
while(i<=5)
{ sem_wait(&blank_number); pthread_mutex_lock(&lock);
queue[p] = rand()%899+101;printf("Produce2 %d/n", queue[p]);
printf("生产100-1000以内的随机数,放入缓冲区中 /n");p = (p+1)%NUM;
pthread_mutex_unlock(&lock);sleep(rand()%5); sem_post(&product_number); i++;}}
void *consumer1(void *arg)//显示输出
{int i=1;
while(i<=5)
{ sem_wait(&product_number); pthread_mutex_lock(&lock);
if(queue[c]<100)//判断取出的数据是字母还是数字,然后分别显示输出
{printf("Consume1 %c/n", queue[c]); printf("取出大写字母/n");}
else
{printf("Consume1 %d/n", queue[c]); printf("取出数字/n");}
c = (c+1)%NUM;pthread_mutex_unlock(&lock);sleep(rand()%5);
sem_post(&blank_number); i++;}}
void *consumer2(void *arg)//变成小写输出
{int i=1;
while(i<=5)
{ sem_wait(&product_number); pthread_mutex_lock(&lock);
if(queue[c]>100)//判断取出的数据是字母还是数字,如果是字母就变成小写输出,如果是数字就原样输出
{printf("Consume2 %d/n", queue[c]); printf("原先是数字,原样输出/n ");}
else
{printf("Consume2 %c/n", tolower(queue[c])); printf("原先是大写字母 ,变成小写输出/n");}c = (c+1)%NUM; pthread_mutex_unlock(&lock);sleep(rand()%5);
sem_post(&blank_number); i++;}}
int main(int argc, char *argv[])
{ pthread_t p1id, c1id,p2id,c2id; sem_init(&blank_number, 0, NUM);
sem_init(&product_number, 0, 0); pthread_create(&p1id, NULL, producer1, NULL);
pthread_create(&c1id, NULL, consumer1, NULL);pthread_create(&p2id, NULL, producer2, NULL); pthread_create(&c2id, NULL, consumer2, NULL);
pthread_join(p1id, NULL);pthread_join(c1id, NULL);
pthread_join(p2id, NULL);pthread_join(c2id, NULL); sem_destroy(&blank_number);
sem_destroy(&product_number);return 0;}
运行结果: