C++ object creation and thread safety
Posted: Fri Feb 18, 2005 5:10 am
I just saw something very interesting and I wanted to tell someone.
I have a class hierarchy: Thread -> Looper -> Window (ancestor to descendant). And the Looper implements the Thread so that it can run itself (waiting on IPC) in a separate context and the main Application can continue. So, if the Looper thread receives an IPC, it can immediately respond to it while the Application is unaware and doing something else.
My instantiation goes like this:
Window() : Looper() : Thread()
And the Thread is set running before Looper() has finished Constructing.
If a context switch occurs before the Looper() constructor is finished, the actual object is still regarded as only a Thread (with a pure virtual run()) method which Looper was supposed to be overriding.
So, when my Thread stub calls (object)->run()), it looks up in the vtable (which is still only set up to be a Thread) and calls run.. the pure virtual function.
Basically, this means that the object must be fully constructed before anything starts using it.
... err ... which actually sounds very obvious now that I think about it.
But anyway...
I have a class hierarchy: Thread -> Looper -> Window (ancestor to descendant). And the Looper implements the Thread so that it can run itself (waiting on IPC) in a separate context and the main Application can continue. So, if the Looper thread receives an IPC, it can immediately respond to it while the Application is unaware and doing something else.
My instantiation goes like this:
Window() : Looper() : Thread()
And the Thread is set running before Looper() has finished Constructing.
If a context switch occurs before the Looper() constructor is finished, the actual object is still regarded as only a Thread (with a pure virtual run()) method which Looper was supposed to be overriding.
So, when my Thread stub calls (object)->run()), it looks up in the vtable (which is still only set up to be a Thread) and calls run.. the pure virtual function.
Basically, this means that the object must be fully constructed before anything starts using it.
... err ... which actually sounds very obvious now that I think about it.
But anyway...