Boost logo

Boost Users :

From: Howard Hinnant (hinnant_at_[hidden])
Date: 2008-01-07 13:05:10


On Jan 7, 2008, at 7:16 AM, Chameleon wrote:

> I have a strange problem with the code below.
>
>> From outside the function operator()(), I can have the pointer to
> thread object 'thread'.
>> From inside operator()() 'thread' is always 0.
>
> Why does this happen?
>
> ------------------------------------------------------------------
> #include <cstdio>
> #include <boost/thread/thread.hpp>
>
> class A
> {
> boost::thread *thread;
>
> public:
> A() : thread(0) {}
> ~A() { join(); }
>
> void createThread() { thread = new boost::thread(*this); }
>
> void operator()() {
> printf("Starting thread with pointer: %d\n",
> thread); //<<<<<<<<<<<<<<HERE!
> delete thread; thread = 0;
> }
>
> void join() { if (thread) thread->join(); }
> };
>
> int main(int, char**) {
> A a;
> a.createThread();
> a.join();
> return 0;
> }

When you create "a", thread is 0. Inside of createThread you *first*
copy *this, passing the copy to create a boost::thread, and *then*
assign the local thread* a value.

-Howard


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net