创建带有boost :: bind()的boost :: thread或不创建 [英] Creating a boost::thread with boost::bind() or without
问题描述
有些人似乎使用boost :: bind()函数启动boost :: threads,就像在以下问题的公认答案中一样:
Some people seem to launch boost::threads using the boost::bind() function, like in the accepted answer of the following question:
其他人根本不使用它,例如在对该问题最支持的答案中:
Whereas other people don't use it at all, like in the answer with the most upvotes of this question:
那么,如果存在的话,有什么区别?
So, what's the difference, if it exists?
推荐答案
如下面的代码所示,该代码可以编译并提供预期的输出,对于使用带有自由功能的boost :: thread,boost :: bind完全没有必要,成员函数和静态成员函数:
As you can see by the code below that compile and gives the expected output, boost::bind is completely unnecessary for using boost::thread with free functions, member functions and static member functions:
#include <boost/thread/thread.hpp>
#include <iostream>
void FreeFunction()
{
std::cout << "hello from free function" << std::endl;
}
struct SomeClass
{
void MemberFunction()
{
std::cout << "hello from member function" << std::endl;
}
static void StaticFunction()
{
std::cout << "hello from static member function" << std::endl;
}
};
int main()
{
SomeClass someClass;
// this free function will be used internally as is
boost::thread t1(&FreeFunction);
t1.join();
// this static member function will be used internally as is
boost::thread t2(&SomeClass::StaticFunction);
t2.join();
// boost::bind will be called on this member function internally
boost::thread t3(&SomeClass::MemberFunction, someClass);
t3.join();
}
输出:
hello from free function
hello from static member function
hello from member function
构造函数中的内部绑定会为您完成所有工作.
The internal bind in the constructor does all the work for you.
仅添加了一些关于每种函数类型会发生什么的额外注释. (希望我已经正确地阅读了源代码!)据我所知,在外部使用boost :: bind不会导致它也加倍并在内部被调用,因为它将按原样通过.
Just added a few extra comments on what happens with each function type. (Hopefully I've read the source correctly!) As far as I can see, using boost::bind externally will not cause it to also double up and be called internally as it will pass through as is.
这篇关于创建带有boost :: bind()的boost :: thread或不创建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!