On Wed, Dec 3, 2008 at 10:34 PM, Steven Watanabe
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