1

我是 Boost 编程的新手。我想要做的是从 main() 创建一个线程,它将连续运行直到 main() 退出。现在,我正在对该线程进行一些操作,完成后它将设置一个布尔标志。main() 将等待这个标志被设置,当它为“真”时,main() 将完成它的工作,重置标志,并等待它再次被设置。另一个线程将连续运行。

谁能提供一组简单的提升线程指令来实现这一目标?

我正在尝试用伪代码做到这一点

class Call {
public:
    bool flag, do_it;
    keyboard_callback() {
        if('s' pressed) do_it = true;
    }
    f() { // some callback function
        if(do_it == true) flag=true;
    }
    void func() {
        ...register callback f()
        ...register keyboard_callback()
        ...
        while(some condition) { keep running , exit when 'q'}
        ...
    }
};
main()
{
    Call obj;
    boost::thread th (boost::bind(&Call::func, &obj));
    th.detach();
    while(true) {
        while (obj.flag == false);
        ...do something
    }
 }
4

1 回答 1

0
// shared variables
boost::mutex mutex;
boost::condition_variable condition;
bool flag = false;

// signal completion
boost::unique_lock<boost::mutex> lock(mutex);
flag = true;
condition.notify_one();

// waiting in main method
boost::unique_lock<boost::mutex> lock(mutex);
while (!flag) {
    condition.wait(lock);
}
于 2012-10-19T18:27:51.500 回答