Should the ctor and dtor object be on the same topic?

With C ++ RAII dtor is called when the object goes out of scope. Multithreading mechanisms always include sending a callback to start on a new thread. Thus, I do not consider it possible to create an object in one thread and destroy it in another, since they must be different areas.

I'm right? Or are there cases where the ctor and dtor objects can be called on different threads?

+3


source to share


2 answers


Thus, I do not consider it possible to create an object in one thread and destroy it in another, since they must be different areas.

How am I right?

Not. These functions can be called completely independent of any threads.

Or are there cases where the ctor and dtor objects can be called on different threads?



Of course there are cases (just bread and butter). Think of a simple producer / consumer model and exchange messages between threads via a queue.

The producer projector instantiates the message and queues it up. The consumer takes it from the queue and the message destructor is called after it has been processed.

+3


source


Multithreading mechanisms always include sending a callback to start on a new thread.

False. There are many cases where you just need another thread to do something or run something in the background, but don't care about the status. In addition, besides callbacks, there are other signaling methods (just one example: condition variables ).

Side note: the callback can be called on any thread, including the thread you passed the callback to. It all depends on how you design the system. You don't need to create a new thread every time you call the callback (although this is one way to do it).



Thus, I do not consider it possible to create an object in one thread and destroy it in another, since they must be different areas.

False. Shared pointers allow pointers to objects to be streamed and after all object references have been removed, then the object is destroyed.

An example would be a network thread that creates an object to represent some message received from the network. This thread then puts this object on the public queue, and some other processing processes process this message. Once the processing thread has finished, it can destroy the object and free up resources for other things.

+3


source







All Articles