Boost logo

Boost Users :

Subject: Re: [Boost-users] How to pass a shared_ptr to a thread.
From: Jason Cipriani (jason.cipriani_at_[hidden])
Date: 2008-12-03 22:48:19


On Wed, Dec 3, 2008 at 10:34 PM, Steven Watanabe <watanabesj_at_[hidden]> wrote:
> AMDG
>
> Jason Cipriani wrote:
>>
>> Hi, I'm new to boost. I'm using it for the shared_ptr implementation.
>> I have a usage question. On Windows, a thread function takes a void*
>> parameter. If I have a shared_ptr to an object, what's the correct way
>> to pass that to a new thread? E.g.:
>>
>> <snip>
>>
>> Sorry if this is a stupid question, but the only thing I could think
>> of was "(LPVOID)new shared_ptr(p)", but that means each thread must
>> explicitly delete the new shared_ptr and that kind of defeats the
>> purpose!
>>

Thanks for the quick reply.

> One solution would be to use Boost.Thread...

It's too late to refactor, unfortunately.

> Another would be to have the thread function immediately copy the
> shared_ptr to a local variable and delete the one on the heap.

This is the way I'll do it, that's a good idea. It's not what I was
hoping for but I guess it's not that bad, it's easy to understand, and
it does what I want, thanks!

> Finally, you could use enable_shared_from this, to allow a shared_ptr
> to be recovered from a raw pointer.

Hmm, is there a way to do something like this (the following code is broken):

class Item : public enable_shared_from_this<Item> { ... };

DWORD WINAPI threadproc (LPVOID vitem) {
  shared_ptr<Item> s = ((Item *)vitem)->shared_from_this();
  ...
}

void start5threads () {
  shared_ptr<Item> p(new Item);
  CreateThread(..., &threadproc, (LPVOID)p.get(), ...);
  CreateThread(..., &threadproc, (LPVOID)p.get(), ...);
  CreateThread(..., &threadproc, (LPVOID)p.get(), ...);
  CreateThread(..., &threadproc, (LPVOID)p.get(), ...);
  CreateThread(..., &threadproc, (LPVOID)p.get(), ...);
}

... that doesn't require any special synchronization to avoid 'p' in
start5threads going out of scope (and deleting the Item) before 's' is
initialized in any of the threads?

I've got the solution though now, thanks again!
Jason


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