将类方法绑定到线程

猫王杜克

查看以下代码段:

struct Event
{
    void event1( time_t t );
    void event2( int, int );
}

Event* f = ...;

time_t t; int i1, int i2;

// 1st
std::thread t{ std::bind( &Event::event1, f, std::placeholders::_1 ), t };
std::thread t{ std::bind( &Event::event2, f, std::placeholders::_1, std::placeholders::_2 ), i1, i2 };

// 2nd method
std::thread t{ &Event::event1, f, t };
std::thread t{ &Event::event2, f, i1, i2 };

第一种方法和第二种方法之间的区别。哪种方法更好?

吸毒者

第一种方法使用围绕函数,它们的Event实例和各自的参数创建一个调用包装std::bind然后,将这些调用包装传递给线程对象。

第二种方法将函数,Event实例和参数直接传递给线程对象。

两种方法的结果将相同,尽管第一种方法对我来说似乎执行了不必要的步骤。

使用std::bind时,你需要,而不是绕过包装的各个参数,例如:

auto func = std::bind(&Event::event1, f, std::placeholders::_1);

functionTakingCallable(func);
functionTakingCallable2(func);
std::thread t(func, arg);

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章