📄 productor&consumer.txt
字号:
#include <stdio.h>
#include <pthread.h>
#include <sys/types.h>
#include <linux/sem.h>
#include <unistd.h>
void p(int semid,int index)
{
struct sembuf sem;
sem.sem_num = index;
sem.sem_op = -1;
sem.sem_flg = 0;
semop(semid,&sem,1);
return;
}
void v(int semid,int index)
{
struct sembuf sem;
sem.sem_num = index;
sem.sem_op = 1;
sem.sem_flg = 0;
semop(semid,&sem,1);
return;
}
#define N 5
int a[N];
int semid;
int in,out;
void *producer(void *arg)
{
int i,j;
i=5;
while(i--)
{
p(semid,1);
p(semid,0);
a[in]=i+1;
printf("producer %d produce the %dth data %d ",pthread_self(),in,a[in]);
for(j=0;j<N;j++)
printf("%d ",a[in]);
printf("\n\n");
in=(in+1)%N;
v(semid,0);
v(semid,2);
sleep(3);
}
}
void *consumer(void *arg)
{
int i,j,s;
i=5;
while(i--)
{
p(semid,2);
p(semid,0);
s=a[out];
printf("consumer %d consume the %dth data %d ",pthread_self(),out,a[out]);
a[out]=0;
for(j=0;j<N;j++)
printf("%d ",a[out]);
printf("\n\n");
out=(out+1)%N;
v(semid,0);
v(semid,1);
sleep(3);
}
}
int main(void)
{ union semun semopts;
int res,i;
pthread_t t1[2],t2[2];
semid = semget(300,3,IPC_CREAT|0666);
if (semid<0)
{
printf("error");
return;
}
semopts.val=1;
res=semctl(semid,0,SETVAL,semopts);
if (res<0) return;
semopts.val=N;
res=semctl(semid,1,SETVAL,semopts);
if (res<0) return;
semopts.val=0;
res=semctl(semid,2,SETVAL,semopts);
if (res<0) return;
for(i=0;i<2;i++)
{
if(pthread_create(&t1[i],NULL,producer,NULL))
printf("error creating thread");
}
for(i=0;i<2;i++)
{
if(pthread_create(&t2[i],NULL,consumer,NULL))
printf("error creating thread");
}
for(i=0;i<2;i++)
{
pthread_join(t1[i],NULL);
pthread_join(t2[i],NULL);
}
semctl(semid,0,IPC_RMID,0);
semctl(semid,1,IPC_RMID,0);
semctl(semid,2,IPC_RMID,0);
exit(0);
}
producer 2184532116 produce the 0th data 5 5 5 5 5 5
producer 2184532117 produce the 1th data 5 5 5 5 5 5
producer 2184532118 produce the 0th data 5 0 0 0 0 0
producer 2184532119 produce the 1th data 5 0 0 0 0 0
producer 2184532120 produce the 2th data 4 4 4 4 4 4
producer 2184532121 produce the 3th data 4 4 4 4 4 4
producer 2184532122 produce the 2th data 4 0 0 0 0 0
producer 2184532123 produce the 3th data 4 0 0 0 0 0
producer 2184532124 produce the 4th data 3 3 3 3 3 3
producer 2184532125 produce the 0th data 3 3 3 3 3 3
producer 2184532126 produce the 4th data 3 0 0 0 0 0
producer 2184532127 produce the 0th data 3 0 0 0 0 0
producer 2184532128 produce the 1th data 2 2 2 2 2 2
producer 2184532129 produce the 2th data 2 2 2 2 2 2
producer 2184532130 produce the 1th data 2 0 0 0 0 0
producer 2184532131 produce the 2th data 2 0 0 0 0 0
producer 2184532132 produce the 3th data 1 1 1 1 1 1
producer 2184532133 produce the 4th data 1 1 1 1 1 1
producer 2184532134 produce the 3th data 1 0 0 0 0 0
producer 2184532135 produce the 4th data 1 0 0 0 0 0
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -