gpt4 book ai didi

c - 使用 sys 信号量进行输出同步

转载 作者:太空宇宙 更新时间:2023-11-04 04:26:44 25 4
gpt4 key购买 nike

#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include "display.h"
#include <sys/ipc.h>
#include <sys/sem.h>

int main()
{
int i;
struct sembuf up = {0,1,0};
struct sembuf down = {0,-1,0};
int sem0 = semget(IPC_PRIVATE,1,0600);
int sem1 = semget(IPC_PRIVATE,1,0600);
if (fork())
{
for (i=0;i<10;i++)
display("ab");
semop(sem1,&up,1);
semop(sem0,&down,1);
wait(NULL);
}
else
{
for (i=0;i<10;i++)
semop(sem1,&down,1);
display("cd\n");
semop(sem0,&up,1);
semop(sem1,&down,1);
}
semctl(sem0,0,IPC_RMID);
semctl(sem1,0,IPC_RMID);
return 0;
}

我希望输出是
abcd
abcd
abcd
...
没有信号量,我得到的不是困惑的输出。上面的代码是我到目前为止所做的,但它似乎不起作用,因为我没有正确放置起伏,我想。我是整个过程同步和互斥主题的新手,这是练习的一部分,因此无法更改任何与信号量无关的代码。如果您能详细说明您的答案,那就太好了。

编辑:如果需要,这是头文件中的显示函数。

void display(char *str)
{
char *p;
for (p=str; *p; p++)
{
write(1, p, 1);
usleep(100);
}
}

最佳答案

您的代码中存在一些问题,请引用代码中的注释进行说明。

int main()
{
int i;
struct sembuf up = {0,1,0};
struct sembuf down = {0,-1,0};
int sem0 = semget(IPC_PRIVATE,1,0600);
int sem1 = semget(IPC_PRIVATE,1,0600);
if (fork())
{
for (i=0;i<10;i++)
{
display("ab");
semop(sem1,&up,1);
semop(sem0,&down,1);
//wait(NULL); //MAYUR: wait() suspends the execution until one of its children terminates. But this was unnecessary here. I removed it.
} //MAYUR: There was no brackets for "for loop". Added it in both the blocks.
}
else
{
for (i=0;i<10;i++)
{
semop(sem1,&down,1);
display("cd\n");
semop(sem0,&up,1);
//semop(sem1,&down,1); //MAYUR: You are doing wait for sem1 in two places. This is was leading to deadlock. Removed it.
}
}
semctl(sem0,0,IPC_RMID);
semctl(sem1,0,IPC_RMID);
return 0;
}

输出:

abcd
abcd
abcd
abcd
abcd
abcd
abcd
abcd
abcd
abcd

关于c - 使用 sys 信号量进行输出同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40822567/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com