问题
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?
For example:
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;
}
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:
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.
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?
Thanks.
回答1:
I believe what you need is pthread condition variable, a synchronization device:
A condition (short for ‘‘condition variable’’) is a synchronization device that allows threads to suspend execution and relinquish the processors until some predicate on shared data is satisfied. The basic operations on conditions are: signal the condition (when the predicate becomes true), and wait for the condition, suspending the thread execution until another thread signals the condition.
来源:https://stackoverflow.com/questions/22090545/resume-a-program-if-variables-value-changes