自己传输代码呀

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <syspes.h>
#include <sysat.h>
#include <semaphore.h>
#include <sys/ipc.h>
#include <fcntl.h>
const int pn = 10, cn = 8, pool = 6;
int front = 0, rear = 0, t[6];
sem_t *empty;
sem_t *full;
sem_t *mutex;
void *producer(void *arg) {
int k = (int) arg + 1;
while (1) {
sleep(2);
sem_wait(empty);
sem_wait(mutex);
t[rear] = 1;
rear = (rear + 1) % pool; //循环队列,且最后一个单元废弃不用
printf(“生产者%d生产了一个产品!此时产品域中的产品数为%d\n”,k,(rear-front+pool)%pool);
fflush(stdout);
sem_post(mutex);
sem_post(full);
sleep(2);
}
}

void *consumer(void *arg) {
int k = (int)arg + 1; //参数是从0开始,故这里加一
while (1) {
int pro;
sleep(2);
sem_wait(full);
sem_wait(mutex);
pro = t[front];
t[front] = 0;
front = (front + 1) % pool;
printf(“消费者%d消费了一个产品!此时产品域中的产品数为%d\n”,k,(rear-front+pool)%pool);
fflush(stdout);
sem_post(mutex);
sem_post(empty);
sleep(2);
}
}

int main() {
pthread_t pid[pn];
pthread_t cid[cn];
mutex = sem_open(“mutex”,O_CREAT,0666,1);
empty = sem_open(“empty”,O_CREAT,0666,pool-1);
full = sem_open(“full”,O_CREAT,0666,0);
sem_init(empty, 0, pool-1); //以免上次程序没有正常quit导致的信号量未被收回
sem_init(mutex, 0, 1);
sem_init(empty, 0, full);
for (int j = 0; j<pn || j<cn; j++) {
if (j < pn) {
pthread_create(&pid[j], NULL, producer, (void*)j);
}
if (j < cn) {
pthread_create(&cid[j], NULL, consumer, (void*)j);
}
}
for (int i=0; i<pn; i++) pthread_join(pid[i], NULL);
for (int j=0; j<cn; j++) pthread_join(cid[j], NULL);
sem_close(mutex);
sem_close(empty);
sem_close(full);
sem_unlink(“mutex”);
sem_unlink(“empty”);
sem_unlink(“full”);
exit(0);
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值