【发布时间】:2015-01-02 12:31:06
【问题描述】:
我需要解决一个被描述为
的问题有两个进程 p1, p2 和两个变量 x , y 进程 p1 和 p2 应该更新 x 和 y 的值,因为 p1 将更新 y = x + 1 并且 p2 将更新 x = y + 1 并保持一致性。即当 p1 同时读取 x 时,p2 无法写入 x 的更新值,而当 p1 同时写入 y 时,p2 无法读取 y 的值。
通过查看问题,我们可以观察到存在死锁。 (read-x by p1)-->(read-y by p1) -->(update-y by p1)-->(read-y by p2)-->(read-x by p2) --> (update-x by p2 )
为了解决死锁,我编写了一个使用信号和共享内存的程序。
在主函数中,信号处理程序使用SIGUSR1 and SIGUSR2 信号编号注册,该信号编号由信号处理程序 func1() 和 func2() 处理。生成的信号也与 x 和 y 的值同步。每当进程 p1 完成它的工作时,它就会为进程 p2 生成一个信号,该信号使用Kill(pid,signo) and vice versa 传输,它们在无限循环中完成工作并休眠一段时间。
它打印正确(一致)的输出,但是这个实现存在问题,因为 最初打印输出需要几秒钟,然后一次打印大量序列(一行)。
应在此代码中进行哪些修改,以便在几乎恒定的时间后打印输出?
有人可能会建议使用等量的睡眠时间,但它不起作用。
void func1(int signo){
*shm2 = *shm1 +1;
cout<<"Value of Y is\t"<<*shm2<<"\n";
signal(signo,func1);
}
void func2(int signo){
*shm1 = *shm2 + 1;
cout<<"Value of X is\t"<<*shm1<<"\n";
signal(signo,func2);
}
int main(){
int pid=0,ppid=0;
int shmid1,shmid2;
signal(SIGUSR1,func1);
signal(SIGUSR2,func2);
shmid1 = shmget(IPC_PRIVATE , sizeof(int) , 0666|IPC_CREAT);
shmid2 = shmget(IPC_PRIVATE , sizeof(int) , 0666|IPC_CREAT);
if(shmid1 < 0 || shmid2 < 0 ){
cout<<"Something goes wrong during creation\n";
exit(1);
}
// Attach shared memory to an address
shm1 = (int *) shmat(shmid1 , (void*)0 , 0);
shm2 = (int *) shmat(shmid2 , (void*)0 , 0);
if( *shm1 == -1 || *shm2 == -1){
cout<<"Memory can't be attached\n";
exit(1);
}
pid = fork();
if(pid < 0 ){
cout<<"fork() error\n";
exit(1);
}
ppid =getppid();
if(pid > 0){
while(1){
sleep(500);
kill(pid,SIGUSR1);
}
}
else{
while(1){
sleep(5);
kill(ppid,SIGUSR2);
}
}
return 0;
}
【问题讨论】:
-
旁注:您是否故意两次拨打
fork?结果是您创建了 4 个进程而不是 2 个。 -
@DiegoNietoCid 复制粘贴出错。我没有打电话给 fork() 。你知道为什么 o/p 会这样吗?
标签: c++ c process signals shared-memory