1

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?

3
  • 3
    It also looks unsafe. Are you passing t before it is initialized? Commented Mar 11, 2014 at 12:31
  • Well, I can do wild_thread t; t.reset(new boost::thread(boost::bind(&thread_routine, t))). Commented Mar 11, 2014 at 12:40
  • @IvanTolstosheyev: No, you can't. You are trying to pass pointer to object that was not allocated yet, which is not possible, because the pointer is not known yet. Commented Mar 11, 2014 at 12:43

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

t is initialized, it is just an empty shared_ptr at the time it is passed to thread_routine, since it has not been assigned yet. For instance passing t by reference (and keeping it alive) would work imo.
@sbabbi Yes it would work, but it would completely refute the purpose of the shared_ptr. Better to share the actual thread-reference then

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.