Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object deleted when its member function is being executed?

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?

like image 480
Laks Avatar asked Aug 09 '13 13:08

Laks


2 Answers

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".

like image 187
Yakk - Adam Nevraumont Avatar answered Oct 18 '22 20:10

Yakk - Adam Nevraumont


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.

like image 21
Michael Goldshteyn Avatar answered Oct 18 '22 20:10

Michael Goldshteyn