Every node class is automatically provided with a class static mutex member variable called “classMutex.” This mutex can sometimes be used as a “quick and dirty” first pass for thread safety. Simply protect each traversal method by locking the class mutex at the beginning of the method, for example:
Locking the class mutex ensures that only one thread can ever be executing this method in any instance of this node. This is helpful if there is a resource owned by the class that is shared by all instances of the class (for example, some scratch space or some cached data).
Using the auto lock class ensures that the mutex will be automatically unlocked before returning from the method. This is much safer than explicitly unlocking the mutex when the method has multiple return points. You should try to avoid recursively locking the mutex. In the example above, if the glRender method calls a utility function, do not lock the mutex again in the utility function.
Note that this approach has a performance penalty in some cases. Because it forces threads to traverse any instance of the node “one at a time,” it reduces the possibility for multiple threads to execute in parallel. Thread local storage can be a better solution (discussed later). |