I have a class which I want to have reference counting. So I added a private reference count variable, and the public methods incRef() and decRef(). The user is responsible for calling incRef and decRef. decRef automatically calls the destructor (with 'delete this') when the reference count reaches zero.
Now I want to make incRef and decRef thread-safe. My first idea is to add a critical section member to the class, and let both incRef and decRef lock the section on entering, and unlock on leaving the method.
One problem is that decRef may delete the object, so the critical section will no longer be available for unlocking. The safest, but not really efficient solution, which I use now for testing purposes, is to use a static critical section member, so that there effectively is a global lock on these operations.
Another problem is the following scenario:
I tried to detect whether this occurs, but I haven't seen it occur. OTOH, I do have another problem: the application locks on a completely different place. Based on the stack in the debugger, the place where it locks seems to be some completely unrelated multithreading code inside either SDL or OpenGL.
FYI: the purpose for all of this is to allow different terrain tiles in libProcTer to share the same crater objects.
Now I want to make incRef and decRef thread-safe. My first idea is to add a critical section member to the class, and let both incRef and decRef lock the section on entering, and unlock on leaving the method.
One problem is that decRef may delete the object, so the critical section will no longer be available for unlocking. The safest, but not really efficient solution, which I use now for testing purposes, is to use a static critical section member, so that there effectively is a global lock on these operations.
Another problem is the following scenario:
- thread A calls decRef, and decRef locks the critical section
- thread B calls incRef, which attempts to lock, and blocks
- thread A finds a zero reference count, and deletes the object
- thread A unlocks the critical section
- thread B attempts to increase the reference count of a no longer existing object
I tried to detect whether this occurs, but I haven't seen it occur. OTOH, I do have another problem: the application locks on a completely different place. Based on the stack in the debugger, the place where it locks seems to be some completely unrelated multithreading code inside either SDL or OpenGL.
FYI: the purpose for all of this is to allow different terrain tiles in libProcTer to share the same crater objects.