Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/60.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C语言中信号量和自旋锁的组合?_C_Concurrency_Semaphore_Spinlock - Fatal编程技术网

C语言中信号量和自旋锁的组合?

C语言中信号量和自旋锁的组合?,c,concurrency,semaphore,spinlock,C,Concurrency,Semaphore,Spinlock,是否可以在C中构建一种组合信号量/自旋锁 也就是说,我想要一个线程控制结构,它支持: 定期唤醒线程以检查某些变量的状态。(像旋转锁) 如果另一个线程(如sem_wait/sem_post)更改了结构的状态,则自动提前唤醒线程 例如,在这样的程序中: 家长: while(something){ //do some stuff here. sem_post(child_sem); sem_wait(parent_sem); } while(something){

是否可以在C中构建一种组合信号量/自旋锁

也就是说,我想要一个线程控制结构,它支持:


  • 定期唤醒线程以检查某些变量的状态。(像旋转锁)
  • 如果另一个线程(如sem_wait/sem_post)更改了结构的状态,则自动提前唤醒线程
例如,在这样的程序中:

家长:

while(something){
    //do some stuff here.
    sem_post(child_sem);
    sem_wait(parent_sem);
}
while(something){
    //do some stuff here.
    sem_post(child_sem);
    while (sem_timed_wait(parent_sem, MAX_WAIT_TIME) == TIMEOUT)
        // check whether you should still continue waiting
}
儿童:

while(something_else){
    sem_wait(child_sem);
    //do some other stuff here.
    sem_post(parent_sem);

}
while(something_else){
    while (sem_timed_wait(child_sem, MAX_WAIT_TIME) == TIMEOUT)
        // check whether you should still continue waiting
    //do some other stuff here.
    sem_post(parent_sem);
}

如果孩子在5秒内未能设置parent_sem,我希望家长取消阻止,但如果孩子提前设置parent_sem,我希望家长在5秒内取消阻止,同时最小化在这5秒内检查和重新检查parent_sem状态所花费的CPU周期数。我知道我可以通过旋转锁来实现这一点,但将等待时间设置为高(即1秒)意味着在大部分时间里浪费几乎1秒的时间。将其设置为低(例如100ms)意味着在孩子超时的情况下进行50次检查。这两种方法都不是很好的解决方案。

这正是定时锁的用途。根据您的库,它们可能可用,也可能不可用

你的例子是:

家长:

while(something){
    //do some stuff here.
    sem_post(child_sem);
    sem_wait(parent_sem);
}
while(something){
    //do some stuff here.
    sem_post(child_sem);
    while (sem_timed_wait(parent_sem, MAX_WAIT_TIME) == TIMEOUT)
        // check whether you should still continue waiting
}
儿童:

while(something_else){
    sem_wait(child_sem);
    //do some other stuff here.
    sem_post(parent_sem);

}
while(something_else){
    while (sem_timed_wait(child_sem, MAX_WAIT_TIME) == TIMEOUT)
        // check whether you should still continue waiting
    //do some other stuff here.
    sem_post(parent_sem);
}
我已经使用这种方法来提高线程的健壮性。也就是说,你不希望你的线程被无限期地阻塞,因为可能有一个错误,你想终止它们,或者你可能只是想让它们退出。另一方面,你会希望尽快醒来


此解决方案同时满足这两个条件。

“定期唤醒线程以检查某个变量的状态。(如旋转锁)”旋转锁有时不会唤醒线程,因为旋转锁是一种锁,当保持时,会使CPU在短时间内旋转(即使用所有CPU),直到释放锁为止。主要是指锁持有的时间非常短。这看起来正是我想要的。谢谢