如果变量的值改变,则恢复程序 [英] Resume a program if variable's value changes

查看:108
本文介绍了如果变量的值改变,则恢复程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在 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?

谢谢。

推荐答案

我相信你需要的是 pthread条件变量,同步ation device:

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.

这篇关于如果变量的值改变,则恢复程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆