问题描述
有没有办法在 c
/ c ++
暂停一个程序(可能与 SIGSTOP
),然后在另一个线程更改某个变量的值时继续( SIGCONT
?)?
Is there a way in c
/c++
to pause a program (might be with SIGSTOP
), and then to continue (SIGCONT
?) it when another thread changes a value of some variable?
例如:
int main(void) {
int a = 0;
createThread(&a); //creates a thread which will change a's value
pauseMyself(); //pauses main process till a's value is changed
/* main process gets here only when a's value has been changed */
fprintf(stderr, "a's value has been changed\n");
return 0;
}
我想看看是否可能,所以我不需要抽样每个间隔 a
的值 - 像 while()
循环,它检查 a
的值每200ms(睡眠200ms)
I want to see if it is possible so I won't need to sample a
's value each interval - Like a while()
loop which checks a
's value each 200ms (sleeps for 200ms)
这个问题的一个可能的解决方案是使用信号量:
One possible solution for this problem is using semaphores:
我应该将信号量初始化为 0
(!),
然后在 main()
,而不是 pauseMyself()
我会做 sem_wait()
,意味着主进程将停止
I should initialize semaphores value to 0
(!),Then in the main()
, instead of pauseMyself()
I'll do sem_wait()
, means that the main process will stop there.
在线程函数中,我会在更改之后执行
的价值,所以主要过程将继续。 sem_post()
In the thread function I'll do sem_post()
after it changes a
's value, so the main process will continue.
还有另一个更好的方法吗?
Is there another, nicer way?
谢谢。
推荐答案
我相信你需要的是,同步ation device:
I believe what you need is pthread condition variable, a synchronization device:
这篇关于如果变量的值改变,则恢复程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!