gpt4 book ai didi

linux - 当关键部分处于循环中以避免死锁时,我是否需要调用 sleep ?

转载 作者:太空狗 更新时间:2023-10-29 11:15:50 26 4
gpt4 key购买 nike

下面是这两个程序的相关代码片段。基本上,消费者从共享缓冲区中取出一个整数,生产者从命令行中取出一个整数。如果没有在循环结束时调用 sleep,就会发生死锁。也就是说,两个进程似乎都在等待信号量。我不明白这是怎么发生的,希望得到解释。另外,让我知道是否有合适的替代方案来替代我的“ sleep 让其他进程有机会”的解决方案。我的直觉告诉我应该有,这是我决定发布这个问题的主要原因。

消费者:

while (get_success == 0) {
// critical section
sem_wait(semaphore);
if (*top != *bottom || *empty == 0) { // not empty
printf("Stored Integer: %d\n", buffer[*bottom]);
*bottom = (*bottom + 1) % N;
if (*bottom == *top)
*empty = 1;
get_success = 1;
}
sem_post(semaphore);
// end critical section
if (get_success == 0)
sleep(1);
}

制作人:

while (ins_success == 0) {
// critical section
sem_wait(semaphore);
if (*top != *bottom || *empty == 1) { // not full
buffer[*top] = atoi(input);
*empty = 0;
*top = (*top + 1) % N;
ins_success = 1;
}
sem_post(semaphore);
// end critical section
if (ins_success == 0)
sleep(1);
}

谢谢!

最佳答案

如果你想强制线程/进程让出 CPU,你可以使用 sched_yield . sleep 将强制调用线程等待,即使它可以继续,比如 0.2 秒后。这当然不是为了避免竞争条件,您需要信号量进行同步。

关于linux - 当关键部分处于循环中以避免死锁时,我是否需要调用 sleep ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9588974/

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