Thread-Safe reference counted smart pointers in c++

Posts: 45
Joined: 2006.11
Post: #1
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. Rasp

Any suggestions, or links for further reading would be appreciated.

Quote this message in a reply
Posts: 5,143
Joined: 2002.04
Post: #2
This is precisely the sort of situation that compare-and-swap is perfect. See my response to your other thread Wink
Quote this message in a reply
Post Reply 

Possibly Related Threads...
Thread: Author Replies: Views: Last Post
  Smart Field Initializers IckyThump 6 6,144 Aug 11, 2009 03:58 PM
Last Post: IckyThump
  Is this safe? NelsonMandella 4 4,348 Jul 27, 2009 01:34 PM
Last Post: NelsonMandella
  Should global variables be pointers or full objects? ia3n_g 1 3,986 Aug 4, 2006 05:53 PM
Last Post: OneSadCookie
  Nifty geometry reference Leisure Suit Lurie 1 3,399 Oct 17, 2005 07:20 AM
Last Post: unknown
  Dangling Pointers/ Memory Leak definitions... WhatMeWorry 1 5,259 Oct 3, 2005 10:43 AM
Last Post: OneSadCookie