Thread-Safe reference counted smart pointers in c++
I am writing a reference counted smart pointer template in c++ as an excercise. However, I'm also beginning to learn about threads, and I don't think these smart pointers are thread safe. The pointer template expects the template parameter to have the Ref(), DecRef(), and RefCount() methods, so the object itself stores its own reference count. I want to ensure that two threads with reference pointers to the same object don't clobber each other.
One idea I've seen is for the smart pointer to return a lightweight proxy object (as a temporary variable) that calls Lock() in its constructor and Unlock() in its destructor on the object being referenced will lock automatically when it is accessed through the smart pointer, but I think this not only takes away flexibility (what if you don't need to lock, ie access read only) and doesn't completely solve the problem, but I don't know enough about threads to know why.
Any suggestions, or links for further reading would be appreciated.
Thanks,
JeroMiya
One idea I've seen is for the smart pointer to return a lightweight proxy object (as a temporary variable) that calls Lock() in its constructor and Unlock() in its destructor on the object being referenced will lock automatically when it is accessed through the smart pointer, but I think this not only takes away flexibility (what if you don't need to lock, ie access read only) and doesn't completely solve the problem, but I don't know enough about threads to know why.

Any suggestions, or links for further reading would be appreciated.
Thanks,
JeroMiya
This is precisely the sort of situation that compare-and-swap is perfect. See my response to your other thread
Possibly Related Threads...
| Thread: | Author | Replies: | Views: | Last Post | |
| Smart Field Initializers | IckyThump | 6 | 2,915 |
Aug 11, 2009 03:58 PM Last Post: IckyThump |
|
| Is this safe? | NelsonMandella | 4 | 2,482 |
Jul 27, 2009 01:34 PM Last Post: NelsonMandella |
|
| Should global variables be pointers or full objects? | ia3n_g | 1 | 2,067 |
Aug 4, 2006 05:53 PM Last Post: OneSadCookie |
|
| Nifty geometry reference | Leisure Suit Lurie | 1 | 2,187 |
Oct 17, 2005 07:20 AM Last Post: unknown |
|
| Dangling Pointers/ Memory Leak definitions... | WhatMeWorry | 1 | 3,484 |
Oct 3, 2005 10:43 AM Last Post: OneSadCookie |
|

