linux实现消费者生产者进程同步,就是生产者生产一个,消费者消费一个。在已有代码上修改。 20
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <errno.h>
#define EXIT_FAILURE -1
#define EXIT_SUCCESS -1
#define SHMSZ 100
#define PATH "/tmp"
int main(void)
{
key_t key;
intshmid;
void *shm;
char *s,c;
key=ftok(PATH,'a');
if((shmid=shmget(key,SHMSZ,IPC_CREAT|0666))<0)
{
perror("shmget error");
exit(EXIT_FAILURE);
}
if((shm=shmat(shmid,NULL,0))==(char *)-1)
{
perror("shmat error");
printf("errno:%d\n",errno);
exit(EXIT_FAILURE);
}
s=shm;
for(c='a';c<='z';c++)
*s++=c;
*s=NULL;
while(*(char*)shm!='*') sleep(1);
shmdt(shm);
exit(EXIT_SUCCESS);
}
消费者代码(consumer.c):
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#define EXIT_FAILURE -1
#define EXIT_SUCCESS 0
#define SHMSZ 100
#define PATH "/tmp"
int main(void)
{
intshmid;
void *shm;
char *s;
key_t key;
key=ftok(PATH,'a');
if((shmid=shmget(key,SHMSZ,0666))<0)
{
perror("shmget error");
exit(EXIT_FAILURE);
}
if((shm=shmat(shmid,NULL,0))==(char *)-1)
{
perror("shmat error");
exit(EXIT_FAILURE);
}
for(s=(char*)shm;*s!=NULL;s++)
putchar(*s);
putchar('\n');
*(char*)shm='*';
shmdt(shm);
exit(EXIT_SUCCESS);
} 展开
2014-12-30
1
自己稍微改改
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include <stdio.h>
#include <pthread.h>
char data[5];//仓库,用于存放char
int size = 0;//库存数
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t full = PTHREAD_COND_INITIALIZER;
pthread_cond_t empty = PTHREAD_COND_INITIALIZER;
void print(){
int i;
for(i=0;i<size;i++){
printf("%c ",data[i]);
}
printf("\n");
}
//生产者线程
void* product(void *p){
char c;
for(c='A';c<='Z';c++){
pthread_mutex_lock(&mutex);//mutex内部才能使用cond
while(size==5) //阻塞生产同时释放互斥 (旋锁)
pthread_cond_wait(&full,&mutex);//阻塞生产线程
printf("PUSH %c\n",c);
data[size] = c;
usleep(10000);
size++;
print();
pthread_cond_broadcast(&empty);//释放消费cond
pthread_mutex_unlock(&mutex);
usleep(200000);
}
}
//消费者线程
void* custom(void *p){
int i;
for(i=0;i<52;i++){
pthread_mutex_lock(&mutex);
while(size==0)
pthread_cond_wait(&empty,&mutex);
printf("POP %c\n",data[size-1]);
size--;
print();
pthread_cond_broadcast(&full);
pthread_mutex_unlock(&mutex);
usleep(400000);
}
}
int main(){
pthread_t id1,id2,id3;
pthread_create(&id1,0,product,0);
pthread_create(&id3,0,product,0);
pthread_create(&id2,0,custom,0);
pthread_join(id1,0); pthread_join(id2,0);
pthread_join(id3,0);
pthread_mutex_destroy(&mutex);
}
亲,对我的代码修改,你这代码不符合我的要求,我要是会改我就改我自己的啦?
广告 您可能关注的内容 |