Ivan Tolstosheyev
Ivan Tolstosheyev

Reputation: 121

boost::make_shared reference to created shared_ptr

I want to make another thread in my application, so I'm doing it that way:

typedef boost::shared_ptr<boost::thread> wild_thread;

void thread_routine(wild_thread t) {
    // do stuff
}
int main() {
    {
        wild_thread t;
        t.reset(new boost::thread(boost::bind(&thread_routine, t)));
    }
    // do other stuff
}

But this is ugly, I need to name this temporary shared_ptr.

So, the question is, can I do this with boost::make_shared anyhow? Can I somehow ask it to bind newly created shared_ptr into my thread_routine? Or maybe there is a better way?

Upvotes: 1

Views: 161

Answers (1)

Wyzard
Wyzard

Reputation: 34581

You can't pass the thread pointer t into your thread_routine with boost::bind because t isn't initialized until after the thread has been created, which is after the boost::bind call has returned.

You should try to avoid needing a pointer to the thread object from within the thread itself. Take a look at the functions in the boost::this_thread namespace instead.

Upvotes: 4

Related Questions