C++ 使用boost线程:发送信号并等待终止

C++ 使用boost线程:发送信号并等待终止,c++,multithreading,boost,C++,Multithreading,Boost,我目前正在编写一个c/c++动态链接库,主要用于Delphi,我对Delphi中的线程比c/c++更熟悉,尤其是boost。因此,我想知道如何实现以下场景 class CMyClass { private: boost::thread* doStuffThread; protected: void doStuffExecute(void) { while(!isTerminationSignal()) //

我目前正在编写一个c/c++动态链接库,主要用于Delphi,我对Delphi中的线程比c/c++更熟悉,尤其是boost。因此,我想知道如何实现以下场景

class CMyClass
{
    private:
        boost::thread* doStuffThread;
    protected:
        void doStuffExecute(void)
        {
            while(!isTerminationSignal()) // loop until termination signal
            {
                // do stuff
            }

            setTerminated(); // thread is finished
        };
    public:
        CMyClass(void)
        {
            // create thread
            this->doStuffThread = new boost::thread(boost::bind(&CMyClass::doStuffExecute, this));
        };

        ~CMyClass(void)
        {
            // finish the thread
            signalThreadTermination();
            waitForThreadFinish();

            delete this->doStuffThread;

            // do other cleanup
        };
}
我有无数关于boost线程、信号和互斥的文章,但我不明白,可能是因为今天是星期五;)还是我认为这样做不可行

问候
Daniel

只需使用原子布尔值来告诉线程停止:

class CMyClass
{
private:
    boost::thread doStuffThread;
    boost::atomic<bool> stop;
protected:
    void doStuffExecute()
    {
        while(!stop) // loop until termination signal
        {
            // do stuff
        }

        // thread is finished
    };
public:
    CMyClass() : stop(false)
    {
        // create thread
        doStuffThread = boost::thread(&CMyClass::doStuffExecute, this);
    };

    ~CMyClass()
    {
        // finish the thread
        stop = true;
        doStuffThread.join();

        // do other cleanup
    };
}
类CMyClass
{
私人:
boost::线程dostufthread;
原子停止;
受保护的:
void doStuffExecute()
{
while(!stop)//循环直到终止信号
{
//做事
}
//线程已完成
};
公众:
CMyClass():停止(false)
{
//创建线程
doStuffThread=boost::thread(&CMyClass::doStuffExecute,this);
};
~CMyClass()
{
//完成线程
停止=真;
doStuffThread.join();
//做其他清理工作
};
}
要等待线程完成,您只需加入它,它将阻塞,直到它完成并可以加入。在销毁线程之前,您需要加入线程,否则它将终止您的程序

无需使用指针和创建带有
new
的线程,只需直接使用
boost::thread
对象即可。在堆上创建任何东西都是浪费、不安全和糟糕的风格

无需使用
boost::bind
将参数传递给
线程
构造函数。多年来,
boost::thread
一直支持直接向其构造函数传递多个参数,并在内部进行绑定

重要的是,在创建新线程之前,
stop
已初始化为
false
,否则,如果新线程很快生成,它可能会在初始化之前检查
stop
的值,并且可能会从未初始化的内存中读取
true
值,然后它就永远不会进入循环


在文体上,许多C++程序员认为写代码< Fo>(Value:Value:Value>)是一种讨厌的憎恶行为。如果您想说您的函数不带参数,那么只需编写
foo()

我将声明“volatile bool needStop”变量,并使用thread::join等待在您将needStop设置为true后实际停止的线程。@VadimKalinsky,no<代码>易失性不适用于多线程。使用
std::atomic
。未定义行为的哪一部分与您无关?如果没有原子,编译器可以将循环转换为:
if(!stop)while(true){/*do work*/}
,因为它知道正在读取的非原子、非易失性变量不能更改,除非在具有未定义行为的程序中,所以它可以假定它永远不会更改请参阅我以前的注释或读取。仅仅因为你不理解这个问题并不意味着它是不真实的。第2.3节中也正是这种情况。这两个链接是由世界上顶尖的数据竞赛和多线程专家编写的,但是,嘿,也许他们只是偏执狂,你是正确的。<代码>易失性<代码>对于C++中的线程间通信来说既不必要也不充分。BrandonKohn多线程是单线程,就像相对论是经典力学一样。你对事件的同时性和顺序的直觉不会持续下去。此外,你所引用的关于种族条件的问答并不是C++特定的。对于C++,标准有一个非常精确的声明,这是这里唯一的相关引用。