|
Threads-Devel : |
Subject: [Threads-devel] Bind question for member functions
From: David Eaves (ideaves_at_[hidden])
Date: 2009-01-08 12:15:58
I took the canonical boost threads example using bind to create threads
from a function object, in which to execute a member function of some
application class.
For example, when I specify the following, it should compile and work
just the same as the simpler example, where count() has file scope. I
took care to create local copies of the function ptr objects, as has
been suggested in several threads. Since bind is supposed to create a
copy of the function ptr, my creation of two local copies is probably
overkill. But anyway, once the function pointer is to a member of foo
instead of the simpler case, it will no longer compile.
#include <boost/thread/thread.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/bind.hpp>
class foo {
public:
foo();
~foo();
int do_foo_stuff();
void do_one_foo_task(int id);
};
foo::foo() { }
foo::~foo() { }
int foo::do_foo_stuff()
{
void (some_api_class::*fp1)(int) = &some_api_class::do_one_foo_task;
void (some_api_class::*fp2)(int) = &some_api_class::do_one_foo_task;
boost::thread thrd1(boost::bind(fp1,1));
boost::thread thrd2(boost::bind(fp2,2));
thrd1.join();
thrd2.join();
}
void foo::do_one_foo_task(int id)
{
boost::mutex::scoped_lock io_mutex;
for (int i=0; i<10; ++i)
{
std::cout << id << ": " << i << std::endl;
}
io_mutex.unlock();
}
int main(int argc, char* argv[])
{
foo *app_object = new foo();
app_object->do_foo_stuff();
delete app_object;
return 0;
}
I get a peculiar looking compile failure related to instantiation
starting at the end of the example's file scope, "instantiated from
here", and cascading through to /usr/include/boost/mem_fn.hpp:333:
error: no matching function for call to 'get_pointer(const &int)'.
Other discussion threads had no conclusive answer and seemed to suggest
that this might be a boost bug. Or claimed that this form should work
fine. Has anybody had an issue like this with threads in boost v1.37.0?
If not, what's the consensus -- should this compile fine and I have
some unrelated make problem? Or am I maybe just using bind incorrectly?
Or, should one avoid creating threads within another member function,
and instead pass in a main-level thread pool to assign tasks? I'd like
to keep the multithreading encapsulated within the class if possible.
Thanks --
DE