问题描述
我目前正在编写一个c / c ++ dll供以后在Delphi中使用,我更熟悉Delphi中的线程比c / c ++和特别是boost。所以我不知道我可以如何实现以下场景?
i'm currently writing a c/c++ dll for later use mostly in Delphi and i'm more familiar with threads in Delphi than c/c++ and especially boost. So i wonder how i can achieve the following scenario?
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线程,信号和互斥,
I have red countless articles about boost threading, signals and mutexes but i don't get it, maybe because it's friday ;) or is it not doable how i think to do it?
回答
丹尼尔
推荐答案
只需使用原子布尔值来告诉线程停止:
Just use an atomic boolean to tell the thread to stop:
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
};
}
要等待线程完成你刚加入它,它是完成和可以加入。
To wait for the thread to finish you just join it, that will block until it is finished and can be joined. You need to join the thread anyway before you can destroy it, or it will terminate your program.
没有必要使用指针,并且创建<$
There is no need to use a pointer and create the thread with new
, just use a boost::thread
object directly. Creating everything on the heap is wasteful, unsafe and poor style.
没有必要使用 boost :: bind
将参数传递给线程
构造函数。许多年来, boost :: thread
已经支持直接向它的构造函数传递多个参数,并且它在内部实现绑定。
There is no need to use boost::bind
to pass arguments to the thread
constructor. For many many years boost::thread
has supported passing multiple arguments to its constructor directly and it does the binding internally.
在创建新线程之前, stop
已经初始化为 false
很重要,否则如果新线程生成非常快,它可以在它被初始化之前检查 stop
的值,并且可能发生从 true
值读取
It's important that stop
has been initialized to false
before the new thread is created, otherwise if the new thread is spawned very quickly it could check the value of stop
before it is initialized, and might happen to read a true
value from the uninitialized memory, and then it would never enter the loop.
在样式主题上,写入 foo(void)
被许多C ++程序员认为是令人厌恶的憎恶。如果你想说你的函数没有参数,只需写 foo()
。
On the subject of style, writing foo(void)
is considered by many C++ programmers to be a disgusting abomination. If you want to say your function takes no arguments then just write foo()
.
这篇关于使用boost线程:信号并等待终止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!