Dan*_*ann 2 c++ multithreading boost
我目前正在编写ac/c ++ dll以供以后在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
};
}
Run Code Online (Sandbox Code Playgroud)
我有关于提升线程,信号和互斥量的红色无数文章,但我不明白,可能是因为它是星期五;)或者我认为这样做是不可行的?
关心丹尼尔
只需使用原子布尔值来告诉线程停止:
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
};
}
Run Code Online (Sandbox Code Playgroud)
要等待线程完成,只需加入它,它将阻塞直到它完成并可以加入.无论如何你需要加入线程才能销毁它,否则它将终止你的程序.
无需使用指针并创建线程new,只需boost::thread直接使用对象即可.在堆上创建所有东西都是浪费,不安全和糟糕的风格.
无需使用boost::bind将参数传递给thread构造函数.许多年来boost::thread一直支持直接将多个参数传递给它的构造函数,并且它在内部进行绑定.
在创建新线程之前stop已经初始化是很重要的false,否则如果新线程很快生成它可以检查stop它在初始化之前的值,并且可能碰巧true从未初始化的内存读取值,然后它会永远不要进入循环.
在风格主题上,foo(void)许多C++程序员认为写作是一种恶心的憎恶.如果你想说你的函数没有参数那么就写foo().
| 归档时间: |
|
| 查看次数: |
2500 次 |
| 最近记录: |