如何正确等待线程中的信号

时间:2016-02-10 12:00:08

标签: c++ multithreading boost

我有类似的代码:

#include  <atomic>
#include <thread>
#include <iostream>

class MyClass
{
    std::thread * m_thread;
    std::atomic_bool m_go;
public:
    MyClass()
    {
        m_thread = nullptr;
    }
    void start()
    {

        m_go = false;

        m_thread= new std::thread([&]()
        {
            try
            {
                std::cout << "waiting" << std::endl;

                while (!m_go)
                {
                    std::this_thread::sleep_for(std::chrono::milliseconds(100));
                }
                std::cout << "Gone!" << std::endl;

            }
            catch (...)
            {
                std::cout << "some error happens" << std::endl;
            }
        });
    }
    void letsGo()
    {
        m_go = true;
    }
    void WaitToFinish()
    {
        if (!m_thread)
        {
            // thread not started or no thread is available
            return ;
        }

        m_thread->join();

                // thread finished, so delete thread and return false;
        delete m_thread;
        m_thread = nullptr;

    }
};




int main()
{
    MyClass myclass;
    std::cout << "starting my class !" << std::endl;
    myclass.start();

    std::this_thread::sleep_for(std::chrono::seconds(10));
    std::cout << "lets my class go!" << std::endl;

    myclass.letsGo();

    myclass.WaitToFinish();

}

MyClass实现了一个可以完成某项工作的线程,但需要等待其他一些操作发生。

使用MyClass的代码首先启动它,然后通过调用方法(在本例中为Go())发信号通知它可以继续。

此代码有效,但我正在寻找更好的解决方案: 1-代码使用无效的循环等待信号。 2-我不确定等待读取和写入m_go是一种有效的方法。

实现此课程的最佳方法是什么?

我可以使用Boost,如果这有助于更好地实现它。

1 个答案:

答案 0 :(得分:3)

准备投资一天左右,了解所有关于std::mutex es和std::condition_variable的内容。

这是一种标准的方法,通常是一个线程等到它收到某种外部信号为止。

您将获得有关http://www.google.com

上的互斥锁和条件变量的所有信息