如何从main()调用线程成员函数

how to call a thread member function from main ( )

本文关键字:调用 线程 成员 函数 main      更新时间:2023-10-16

在编译使用线程的程序时出现错误。这是引起问题的部分。如果有人告诉我是否以正确的方式调用线程函数,那就太好了。

在main.cpp:

int main() 
{
    WishList w;
    boost::thread thrd(&w.show_list);
    thrd.join();
}
在another_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库时遇到问题。我应该尽快试一下

获取成员函数地址的语法是&ClassName::FunctionName,所以应该是&WishList::show_list,但是现在需要一个对象来调用函数指针。最好的(也是最简单的)是使用boost::bind:

#include <boost/bind.hpp>
WishList w;
boost::thread t(boost::bind(&WishList::show_list, &w));

与线程无关,这只是"如何获得指向成员函数的指针"。按编译器说的做,说&WishList::show_list。但是您可能还需要传递实例指针。

更新:是的,使用bind就像Xeo说的。

关于你的标题:注意函数不"属于线程"。类不是线程的一部分。所有线程都访问相同的内存——每个线程都有自己的自动存储空间,但是在类定义中没有任何内容说"这将在单独的线程中"。