I have pointer object to singleton class.
Thread 1: Currently executing a member function of the above said object.
Thread 2: Deletes the above object when the object's member function is still being executed by Thread 1.
What happens to Thread 1 where the member function is being executed? Whether the execution will be stopped midway?
It is probably undefined behavior, unless you are extra careful.
Deleting the object while your thread accesses it in an unordered (non-synchronized, basically) manner is undefined behavior, even if you get lucky.
Accessing the members of the object (not just running a member: actually accessing a member -- calling a member function, reading a member variable, etc) after you have synchronized with the delete from the main thread is also undefined behavior.
If you carefully synchronize with the main thread, then do not access the member data nor call a different member function after that synchronization, and the main thread deletes the object after that synchronization, then you are perfectly ok.
Almost anything short of that results in undefined behavior.
While undefined behavior can do almost anything, it would be unexpected undefined behavior for this to cause the execution of the code in the member function to suddenly stop just because the object is deleted. More likely you'd get segfaults, memory corruption, or the like. What is worse is that in many cases, things would work "just fine".
You will most likely get undefined behavior. Thread 1 can get a seg fault or it may continue merrily on its way if it accesses no member data (and makes no virtual function calls) after the object's deletion. It also depends on what happens to the memory area after deletion. Is it cleared? Is it non-writable/non-readable? It's all highly implementation dependent as well dependent on the data needs of your application in terms of reusing the data area to handle other allocations.
The guidance is to never delete an object until all use of it is complete. There are some exceptions where member functions delete the object they operate on ensuring there is no more member access after the point of deletion. But other than those few cases that actually justify deletion in a member, don't do this.
In the multi-threaded environment you are describing, be absolutely certain to coordinate object lifetime with object use or you may get very difficult to debug (platform dependent and non-deterministic) behavior.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With