boost::thread callback copy problem
Hi, I am new to boost::thread but have come across the following problem and wondered if anyone could help... The problem is the copy overhead used by the boost::thread / boost::function0 code. The following code actually creates multiple copies of myclass rather than using a reference to myclass and due to the size of the class, this leads to a considerable overhead. I only noticed this problem because the thread kept failing due to the fact that my constructor held some socket initialisation code, which was being called multiple times. Is there a way that I can force the thread class to use references rather than copying? Looking at the code for the function library, I see that you can use boost::ref for function classes, any ideas as to how it can be used in the thread class? Thanks in advance Howard Cole www.selestial.com Example code. class myclass { public: // Lots of local data here void operator() () { do_thread_stuff(); }; // CTOR myclass(){ do_some_initialisation_stuff(); }; // DTOR ~myclass(){ do_some_cleanup_stuff(); }; // Lots of member funcs ... }; void main (void){ myclass test_instance; boost::thread test_thread(test_instance); test_thread.join(); }
Doug Gregor wrote:
On Aug 27, 2004, at 4:37 AM, Howard Cole wrote:
myclass test_instance; boost::thread test_thread(test_instance); test_thread.join();
Just change the thread construction to use boost::ref:
boost::thread test_thread(boost::ref(test_instance));
Yep. In addition you might want to consider using shared_ptr, because your ref-enhanced code will now need to keep track of test_instance and ensure that it isn't destroyed before the thread has finished. shared_ptr<myclass> px( new myclass ); thread test_thread( &myclass::do_thread_stuff, px ); You can also use pimpl to hide the shared_ptr in myclass, but the above is easier, and you can make myclass noncopyable.
participants (3)
-
Doug Gregor
-
Howard Cole
-
Peter Dimov