📄 p-c.c
字号:
#define __LIBRARY__#include <unistd.h>#include <stdio.h>_syscall2(sem_t *,sem_open,const char *,name, unsigned int,value);_syscall1(int ,sem_wait , sem_t *,sem);_syscall1(int ,sem_post , sem_t *,sem);_syscall1(int ,sem_unlink,const char *,name);_syscall1(int ,pcinsert,int ,item);_syscall0(int ,pcdelete);#define NR_BUFFERS 10#define NR_Produces 500#define NR_Consumes 50sem_t * mutex;sem_t * empty;sem_t * full;void Producer(int nr_produces){ int i; for(i=0; i<nr_produces; i++) { sleep(1); sem_wait(empty); sem_wait(mutex); pcinsert(i); sem_post(mutex); sem_post(full); }}void Consumer(int nr_consumes){ int i,item; for(i=0; i<nr_consumes; i++) { sleep(1); sem_wait(full); sem_wait(mutex); item=pcdelete(); printf("%d : %d\n",getpid(),item); fflush(stdout); sem_post(mutex); sem_post(empty); }}int main(){ int i; mutex=sem_open("PCMutex", 1); empty=sem_open("PCEmpty", NR_BUFFERS); full=sem_open("PCFull", 0); if(!fork()) { Producer(NR_Produces); exit(5); } for(i=0;i<10;i++) { if(!fork()){ Consumer(NR_Consumes); exit (5);} } }
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -