linuxc问题

FiYOONA 2018-12-24 10:56:53
假设有一个有限缓冲区(包含8个单元)和两个线程:生产者和消费者。下列程序使用信号量来实现生产者和消费者线程之间的同步,请按要求完成下列操作。 1. 将程序补充完整。 2. 编译运行程序,并保存运行结果。 #include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <semaphore.h> #define__________________ void *producer(void *arg); void *consumer(void *arg); int queue[NUMBER]; sem_t blank_number, product_number; int main(int argc, char *argv[]) { pthread_t pid, cid; sem_init(&blank_number, 0, NUMBER); sem_init(&product_number, 0, 0); pthread_create(&pid, NULL, producer, NULL); pthread_create(&cid, NULL, consumer, NULL); pthread_join(pid, NULL); pthread_join(cid, NULL); sem_destroy(&blank_number); sem_destroy(&product_number); } void *producer(void *arg) { int p = 0; while(1) { _______________________________ _______________________________ _______________________________ _______________________________ _______________________________ sleep(_______________); //随机休眠1-5秒钟 } void *consumer(void *arg) { int c = 0; while(1) { _______________________________ _______________________________ _______________________________ _______________________________ _______________________________ sleep(_______________); //随机休眠1-5秒钟 } }
...全文
214 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
无名小卒~ 2019-01-07
  • 打赏
  • 举报
回复
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>

#define NUMBER 1

void *producer(void *arg);
void *consumer(void *arg);

int queue[NUMBER];
sem_t blank_number, product_number;

int main(int argc, char *argv[])
{
	pthread_t pid, cid;
	sem_init(&blank_number, 0, NUMBER);
	sem_init(&product_number, 0, 0);
	pthread_create(&pid, NULL, producer, NULL);
	pthread_create(&cid, NULL, consumer, NULL);
	pthread_join(pid, NULL);
	pthread_join(cid, NULL);
	sem_destroy(&blank_number);
	sem_destroy(&product_number);
}
void *producer(void *arg)
{
	int p = 0;
	while(1)
	{
		sem_wait(&product_number);
		printf("生产1\n");
		sem_post(&blank_number);
		sleep(rand()%5); //随机休眠1-5秒钟
	}
}
void *consumer(void *arg)
{
	int c = 0;
	while(1)
	{
		sem_wait(&blank_number);
		printf("消费1\n");
		sem_post(&product_number);
		sleep(rand()%5); //随机休眠1-5秒钟
	}
}
不明白什么叫有限缓冲区,但是代码大概是这个样子

427

社区成员

发帖
与我相关
我的任务
社区描述
非技术问题的乐园
社区管理员
  • 非技术区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧