开发者

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 .

In main.cpp:

int main() 
{
    WishList w;
    boost::thread thrd(&w.show_list);
    thrd.join();
}

In anoth开发者_高级运维er_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. 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. Best (and easiest) is to use 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. But you may also need to pass the instance pointer along.

Update: Yes, use bind like Xeo says.

Regarding your title: Note that the function does not "belong to the thread". 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".

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜