简体   繁体   中英

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.

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()).

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. 2- I am not sure that waiting reading and writing to m_go is a valid way to do this.

What is the best way to implement this class?

I can use Boost, if that helps to implement it better.

Prepare to invest a day or so learning all about std::mutex es and std::condition_variable s.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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