[英]How to call thread with a public member function from another class as argument
[英]how to call a thread member function from main ( )
编译使用线程的程序时出现错误。 这是导致问题的部分。如果有人告诉我我是否以正确的方式调用线程 function,那就太好了。
在 main.cpp 中:
int main()
{
WishList w;
boost::thread thrd(&w.show_list);
thrd.join();
}
在另一个_file.cpp 中:
class WishList{
public:
void show_list();
}
void WishList::show_list(){
.
.
.
.
}
我收到以下错误
error: ISO C++ forbids taking the address of a bound member function to form a pointer to member function. Say ‘&WishList::show_list’
/home/sharatds/Downloads/boost_1_46_1/boost/thread/detail/thread.hpp: In member function ‘void boost::detail::thread_data<F>::run() [with F = void (WishList::*)()]’:
/home/sharatds/Downloads/boost_1_46_1/boost/thread/detail/thread.hpp:61:17: error: must use ‘.*’ or ‘->*’ to call pointer-to-member function in ‘((boost::detail::thread_data<void (WishList::*)()>*)this)->boost::detail::thread_data<void (WishList::*)()>::f (...)’, e.g. ‘(... ->* ((boost::detail::thread_data<void (WishList::*)()>*)this)->boost::detail::thread_data<void (WishList::*)()>::f) (...)’
编辑:为线程安装 Boost 库时遇到问题。 应尽快尝试此操作
获取成员 function 的地址的语法是&ClassName::FunctionName
,所以它应该是&WishList::show_list
,但是现在你需要一个 object 来调用 ZC1C425268E68384F1AB4ZA 指针。 最好的(也是最简单的)是使用boost::bind
:
#include <boost/bind.hpp>
WishList w;
boost::thread t(boost::bind(&WishList::show_list, &w));
与线程无关,这只是“我如何获得指向成员函数的指针”。 做编译器说的,说&WishList::show_list
。 但是您可能还需要传递实例指针。
更新:是的,像 Xeo 说的那样使用bind
。
关于您的标题:请注意,function 不“属于线程”。 类不是线程的一部分。 所有线程都访问相同的 memory - 每个线程都有自己的自动存储空间,但是 class 定义中没有任何内容说“这在单独的线程中”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.