我目前正在编写一个c/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
};
}
我有无数关于增强线程、信号和互斥体的红色文章,但我不明白,也许是因为今天是星期五;) 或者我认为如何做是不可行的?
问候
丹尼尔
只需使用原子布尔值来告诉线程停止:
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
};
}
要等待线程完成,您只需加入它,这将阻塞,直到它完成并可以加入。无论如何,您需要先加入该线程,然后才能销毁它,否则它将终止您的程序。
无需使用指针并使用以下命令创建线程new
,只需使用一个boost::thread
直接反对。在堆上创建所有内容都是浪费、不安全且风格不佳的行为。
没有必要使用boost::bind
将参数传递给thread
构造函数。许多许多年来boost::thread
支持直接将多个参数传递给其构造函数,并在内部进行绑定。
重要的是stop
已初始化为false
在创建新线程之前,否则如果新线程生成得非常快,它可以检查stop
在初始化之前,可能会碰巧读取true
值来自未初始化的内存,然后它永远不会进入循环。
论风格、写作foo(void)
许多 C++ 程序员认为这是一种令人厌恶的行为。如果你想说你的函数不带参数那么就写foo()
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)