任务描述
本关任务:程序 4-1.c 模拟了 1 个生产者和 1 个消费者,请改写该程序,模拟 5 个生产者和 5 个消费者,它们共享一个包含 8 个缓冲区的缓冲池。产品以 4 位编号,最高位表示生产者编号、其他表示该生产者的产品号,参考输出如下:
程序 4-1.c 中信号量需要在同一行内,否则评测无法通过,而且修改 c 语言程序请在现有的基础上修改!!!
(请将修改之后的程序 4-1.c 保存到 myshixun 文件夹下再点击评测。)
实验准备
4-1.c文件存放在/data/workspace/myshixun/exp3中。
整体命令流程
第一步:找到4-1.c并拖到vscode里打开
第二步:编辑4-1.c代码
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
#define N 10
#define PRODUCT_NUM 10
int buffer[N], readpos = 0, writepos = 0;
sem_t full, empty,mtx,mtx1;
void sleep_random(int t) {
sleep((int)(t * (rand() / (RAND_MAX *1.0))));
}
void *produce(void * arg){
int id = *((int *)arg);
int i;
for (i = 0; i < PRODUCT_NUM; i++){
sleep_random(2);
sem_wait(&empty);
sem_wait(&mtx);
buffer[writepos++] = id*1000 + i + 1;
if (writepos >= N)
{
writepos = 0;
}
printf("produce: %d\n", id*1000 + i + 1);
sem_post(&mtx);
sem_post(&full);
}
}
void *consume(void * arg){
int i;
int id = *((int *)arg);
for (i = 0; i < PRODUCT_NUM; i++){
sleep_random(2);
sem_wait(&full);
sem_wait(&mtx1);
printf("%d consume: %d\n", id, buffer[readpos]);
buffer[readpos++] = - 1;
if (readpos >= N)
readpos = 0;
sem_post(&mtx1);
sem_post(&empty);
}
}
int main(){
int res[10], res1[10], i;
pthread_t t1[8] = {0};
pthread_t t2[8] = {0};
for (i = 0; i < N; i++)
buffer[i] = - 1;
srand((int)time(0));
sem_init(&full, 0, 0);
sem_init(&mtx, 0, 1);
sem_init(&mtx1, 0, 1);
sem_init(&empty, 0, N);
for(i=0;i<5;i++)
{
res[i] = pthread_create(&(t1[i]), NULL, produce, (void *) &i);
if (res[i] != 0){
perror("failed to create thread");
exit(1);
}
}
for(int j=0;j<5;j++)
{
res1[j] = pthread_create(&(t2[j]), NULL, consume, (void *) &j);
if (res1[j] != 0){
perror("failed to create thread");
exit(1);
}
}
pthread_join(t1[0],NULL);
pthread_join(t1[1],NULL);
pthread_join(t1[2],NULL);
pthread_join(t1[3],NULL);
pthread_join(t1[4],NULL);
pthread_join(t2[0],NULL);
pthread_join(t2[1],NULL);
pthread_join(t2[2],NULL);
pthread_join(t2[3],NULL);
pthread_join(t2[4],NULL);
return 0;
}
第三步:打开终端,编译一下
cd /home/headless/Desktop/workspace/myshixun/exp3/
gcc -pthread 4-1.c
./a.out
第四步:复制到这个目录下,再点击测评