当前位置: 技术问答>linux和unix
进程同步问题,求指点
来源: 互联网 发布时间:2017-05-30
本文导语: 问题描述:生产者进程向数组添加100次数据,消费者从数组读取数据并求和,有fullid,emptyid,mutxid三个信号量,array,sum,set,get四个共享主存,array为共享数组,set记录生产者写的次数,get为消费者读的次数. 问题:每个进程...
问题描述:生产者进程向数组添加100次数据,消费者从数组读取数据并求和,有fullid,emptyid,mutxid三个信号量,array,sum,set,get四个共享主存,array为共享数组,set记录生产者写的次数,get为消费者读的次数.
问题:每个进程都运行不完整,好像semop对进程并没有阻塞
代码:
#include
#include
#include
#include
#include
#include
#include
#include
#define MAXSEM 5
int fullid;
int emptyid;
int mutxid;
int main()
{
pid_t prod,custoa,custob;
int shm_id,i = 0;
int flag = IPC_CREAT|IPC_EXCL|00666;
struct sembuf P = {0,-1,SEM_UNDO};
struct sembuf V = {0,1,SEM_UNDO};
union semun arg;
int *array;
int *sum;
int *set;
int *get;
int arr_id,sum_id,set_id,get_id;
arr_id = shmget(IPC_PRIVATE,1024,IPC_CREAT|IPC_EXCL);
sum_id = shmget(IPC_PRIVATE,1024,IPC_CREAT|IPC_EXCL);
set_id = shmget(IPC_PRIVATE,1024,IPC_CREAT|IPC_EXCL);
get_id = shmget(IPC_PRIVATE,1024,IPC_CREAT|IPC_EXCL);
// printf("create share memory successn");
array = (int *)shmat(arr_id,NULL,0);
sum = (int *)shmat(sum_id,NULL,0);
set = (int *)shmat(set_id,NULL,0);
get = (int *)shmat(get_id,NULL,0);
// printf("link successn");
fullid = semget(IPC_PRIVATE,1,flag);
emptyid = semget(IPC_PRIVATE,1,flag);
mutxid = semget(IPC_PRIVATE,1,flag);
arg.val = 0;
if(semctl(fullid,0,SETVAL,arg) == -1)
perror("semctl setval error");
arg.val = MAXSEM;
if(semctl(emptyid,0,SETVAL,arg) == -1)
perror("semctl setval error");
arg.val = 1;
if(semctl(mutxid,0,SETVAL,arg) == -1)
perror("semctl setval error");
// P = {0,-1,IPC_NOWAIT};
// V = {0,1,IPC_NOWAIT};
// printf("%dn",getpid());
prod = fork();
if(prod
问题:每个进程都运行不完整,好像semop对进程并没有阻塞
代码:
#include
#include
#include
#include
#include
#include
#include
#include
#define MAXSEM 5
int fullid;
int emptyid;
int mutxid;
int main()
{
pid_t prod,custoa,custob;
int shm_id,i = 0;
int flag = IPC_CREAT|IPC_EXCL|00666;
struct sembuf P = {0,-1,SEM_UNDO};
struct sembuf V = {0,1,SEM_UNDO};
union semun arg;
int *array;
int *sum;
int *set;
int *get;
int arr_id,sum_id,set_id,get_id;
arr_id = shmget(IPC_PRIVATE,1024,IPC_CREAT|IPC_EXCL);
sum_id = shmget(IPC_PRIVATE,1024,IPC_CREAT|IPC_EXCL);
set_id = shmget(IPC_PRIVATE,1024,IPC_CREAT|IPC_EXCL);
get_id = shmget(IPC_PRIVATE,1024,IPC_CREAT|IPC_EXCL);
// printf("create share memory successn");
array = (int *)shmat(arr_id,NULL,0);
sum = (int *)shmat(sum_id,NULL,0);
set = (int *)shmat(set_id,NULL,0);
get = (int *)shmat(get_id,NULL,0);
// printf("link successn");
fullid = semget(IPC_PRIVATE,1,flag);
emptyid = semget(IPC_PRIVATE,1,flag);
mutxid = semget(IPC_PRIVATE,1,flag);
arg.val = 0;
if(semctl(fullid,0,SETVAL,arg) == -1)
perror("semctl setval error");
arg.val = MAXSEM;
if(semctl(emptyid,0,SETVAL,arg) == -1)
perror("semctl setval error");
arg.val = 1;
if(semctl(mutxid,0,SETVAL,arg) == -1)
perror("semctl setval error");
// P = {0,-1,IPC_NOWAIT};
// V = {0,1,IPC_NOWAIT};
// printf("%dn",getpid());
prod = fork();
if(prod