简体   繁体   中英

How to delete object created in another thread in C++

There is a long-time request and is called from the "main" (UI) thread. It is planned to move it's call into a separate thread. The problem is that some objects are created in this thread on the heap (main thread will have to work with these pointers).

Questions:

  1. Is it allowed to delete 'another-thread' objects in the main thread?
  2. Is it a good idea to delete object in "another" thread.
  1. Yes.

  2. Depending on situation, this is not bad and not good, just do what you need according to your algorithm.

Deleting objects created in another thread may be dangerous only if object destructor works with a thread local storage. This must be mentioned in the class documentation.

There is nothing to prevent you from doing that, although I wouldn't advise for it. You'd better use a shared_ptr or similar object IMHO.

It is safe, but don't forget about race conditions. Delete it like this:

//someObj

   if (someObj != null)
   {
      lock();
         if (someObj != null)
         {
            delete someObj;
            someObj = NULL;
         }
      unlock();
   }

It is a allowed to delete in another thread.
However: it is the programmer's responsability to make sure that the owner is always known. Also, in multithreaded environment, you have to make sure that there are no racing conditions, where another thread still tries to access the object. However, this is also true when the creating thread deletes the object. A good way to solve this is with shared/weak pointers; the boost shared_ptr is thread-safe

You may want to take a look at Boost's shared_ptr . It will handle freeing objects for you, no matter in which thread they were created, and it also saves you the trouble of keeping track of which threads hold a pointer to which objects. It is also totally thread safe (you'll still have to protect the inner workings of your own object, but the rest it will take care for you).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM