[英]how to call a thread member function from main ( )
I'm getting errors while compiling a program that uses threads.编译使用线程的程序时出现错误。 Here is the part that is causing problems.It would be nice if anybody told me if I'm calling the thread function in the right way.
这是导致问题的部分。如果有人告诉我我是否以正确的方式调用线程 function,那就太好了。
In main.cpp:在 main.cpp 中:
int main()
{
WishList w;
boost::thread thrd(&w.show_list);
thrd.join();
}
In another_file.cpp:在另一个_file.cpp 中:
class WishList{
public:
void show_list();
}
void WishList::show_list(){
.
.
.
.
}
I'm getting the following error我收到以下错误
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) (...)’
EDIT: Having problems installing Boost library for threads.编辑:为线程安装 Boost 库时遇到问题。 Shall try this as soon as it works
应尽快尝试此操作
The syntax to take the address of a member function is &ClassName::FunctionName
, so it should be &WishList::show_list
, but now you need an object to call the function pointer on.获取成员 function 的地址的语法是
&ClassName::FunctionName
,所以它应该是&WishList::show_list
,但是现在你需要一个 object 来调用 ZC1C425268E68384F1AB4ZA 指针。 Best (and easiest) is to use boost::bind
:最好的(也是最简单的)是使用
boost::bind
:
#include <boost/bind.hpp>
WishList w;
boost::thread t(boost::bind(&WishList::show_list, &w));
Nothing to do with threads, this is just "how do I obtain a pointer to a member function".与线程无关,这只是“我如何获得指向成员函数的指针”。 Do what the compiler says, say
&WishList::show_list
.做编译器说的,说
&WishList::show_list
。 But you may also need to pass the instance pointer along.但是您可能还需要传递实例指针。
Update: Yes, use bind
like Xeo says.更新:是的,像 Xeo 说的那样使用
bind
。
Regarding your title: Note that the function does not "belong to the thread".关于您的标题:请注意,function 不“属于线程”。 Classes are not part of threads.
类不是线程的一部分。 All threads access the same memory -- each thread has its own space for automatic storage, but there's nothing in a class definition that says "this goes in a separate thread".
所有线程都访问相同的 memory - 每个线程都有自己的自动存储空间,但是 class 定义中没有任何内容说“这在单独的线程中”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.