简体   繁体   English

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

[英]How to wait properly for a signal in a thread

I have a code similar to this: 我有类似的代码:

#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 implemented a thread that do some work, but it needs to wait for some other actions to happen. MyClass实现了一个可以完成某些工作的线程,但是它需要等待其他一些操作发生。

The code which use MyClass would first start it and then signal it that it can continue by calling a method ( in this example Go()). 使用MyClass的代码将首先启动它,然后通过调用方法(在本示例中为Go())向其发出信号,告知它可以继续。

This code works, but I am looking for a better solution that : 1- The code wait for signal using a loop which is not efficient. 这段代码有效,但是我正在寻找一种更好的解决方案:1-该代码使用效率不高的循环来等待信号。 2- I am not sure that waiting reading and writing to m_go is a valid way to do this. 2-我不确定等待读取和写入m_go是执行此操作的有效方法。

What is the best way to implement this class? 实现此类的最佳方法是什么?

I can use Boost, if that helps to implement it better. 我可以使用Boost,如果可以帮助更好地实现它。

Prepare to invest a day or so learning all about std::mutex es and std::condition_variable s. 准备花一天左右的时间学习有关std::mutexstd::condition_variable的所有知识。

This is the standard way to implement, in general, a thread waiting until it receives an external signal of some sort. 通常,这是实现线程等待直到收到某种外部信号的标准方法。

You will all the information you need about mutexes and condition variables on http://www.google.com 您将在http://www.google.com获取所需的关于互斥和条件变量的所有信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM