mercredi 18 janvier 2023

Is it a race condition to start a thread in a constructor [closed]

I've heard arguments both for and against starting background threads in the constructor of classes. The camp that seems to be for it argues that RAII implies we should do all our initialization in a constructor. But I have heard others claim that starting a thread in a constructor is a race condition as the vtable may be mutated if the class is a base class for a derived type. This would mean the thread may start running and calling virtual functions that are in an undefined state at this point. Is this correct? Essentially this boils down to if it's safe to spin up a new thread in a class constructor, or if I need to utilize a Start() function even for classes where I would want a background thread to exist for the class lifetime so the stack can manage it's lifetime and join synchronization behavior.

Aucun commentaire:

Enregistrer un commentaire