2012-12-06 128 views
8

有些人似乎使用boost :: bind()函数启动boost :: threads,就像在以下问题的接受答案中一样:使用boost :: bind()或不使用它创建boost :: thread

Using boost thread and a non-static class function

,而其他人都不在回答这个问题的最upvotes使用它在所有的,如:

Best way to start a thread as a member of a C++ class?

那么,有什么区别,如果它的存在?

+0

所以我认为你真的在问为什么使用Boost来处理(本地)p线程的线程? – ScoPi

+2

@ScoPi:不,我想他是问为什么要使用'bind'而不是让'boost :: thread'构造函数完成所有工作。 (如果你想使用'shared_ptr'来启动线程,我很确定你需要使用'bind'。) –

回答

9

正如你可以通过编译下面的代码中看到,并给出了预期的输出,提高::绑定是使用boost ::线程提供免费功能,成员函数和静态成员函数完全没有必要:

#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 

构造函数中的内部绑定为您完成所有工作。

刚刚添加了几个额外的评论,每个函数类型会发生什么。 (希望我已经正确地阅读了源文件!)据我所知,使用boost :: bind external.The不会导致它加倍并在内部调用,因为它会按原样传递。

+1

那么为什么人们使用它呢?这个boost :: asio示例也使用bind():http://www.boost.org/doc/libs/1_52_0/doc/html/boost_asio/example/chat/chat_client.cpp – deinocheirus

+0

@ user1613它可能取决于版本的提升。没有'std :: bind'的变体需要某种可变模板模拟。 – juanchopanza

+0

至少可以追溯到2008年安东尼威廉斯博士Dobbs关于Boost.Thrads的文章:http://www.drdobbs.com/cpp/whats-new-in-boost-threads/211600441我怀疑人们纯粹是出于习惯。不用看源代码,这可能意味着boost :: bind在外部使用时会被调用两次。 – goji

1

boost::bind用于将成员函数绑定到线程,而没有使用boost :: bind通常您使用的是静态函数或带有线程的自由函数。

0

主要区别在于您是要接口静态还是非静态成员函数。如果要将非静态成员函数用作线程启动的函数,则必须使用类似bind之类的内容。

建议的替代方案(链接的第二个问题)是使用一个静态方法,该方法接受一个指向类对象的指针,然后可以调用它的任何成员。这略微清理了语法,但最大的好处(对我来说)是,您不需要包含Boost之类的内容即可得到bind。但是,如果您使用的是boost::threads,那么您也可以使用boost::bind。注意,C++ 11 std::bind,所以你可以使用bindpthreads以及不引入任何额外的依赖,如升压,但这是,如果你想使用C++ 11

我看不出一个令人信服的语法理由,以避免使用bind而不是使用调用成员函数的静态方法。但这更多是个人喜好的问题。

1

那么,它有什么区别?

主要区别是你需要在线程函数中访问什么。

如果您的设计需要您访问一个类实例的数据,然后启动你的线程作为一个类的实例(使用boost::bindthis和成员函数,或映射到this一个void*静态成员函数的一部分 - 这是一个大多数是风格问题)。

如果您的设计要求线程函数不依赖于特定对象的数据,那么请使用免费函数。

相关问题