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

标签 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,如果这有助于更好地实现它的话。

最佳答案

准备花一天左右的时间学习所有关于 std::mutexstd::condition_variable 的知识。

通常,这是实现线程等待直到它接收到某种外部信号的标准方法。

您将在 http://www.google.com 上获得有关互斥锁和条件变量的所有信息。

关于c++ - 如何正确等待线程中的信号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35314667/

相关文章:

c++ - 如何在 BGL 图中获取 OutEdgeList

c++ - 何时捕获 boost::bad lexical_cast

c++ - 为什么 std::weak_ptr::expired 被优化掉了?

Java静态线程安全

c++ - 为什么 cout 在代码块上没有产生输出?

c++ - 如何在 VC++ 2010 中使用 .dll 文件启动进程

C++ - 如何分块文件以进行同步/异步处理?

boost - 为什么我们需要 boost::thread_specific_ptr?

c++ - 服务定位器实现

c++ - C/C++ - posix_memalign()