简体   繁体   中英

Synchronize access and delete item in a list from different threads.

I have a list of objects. While one thread will add or remove objects in this list depending on some conditions. While other thread will access objects in this list. Ex:

List<node*> list


Thread1:

 {
   list.append(node);
   list.removeOne(index);
   ............

 }
Thread2
{

   Node* node = list.at(index);
   if(node)
     doSomething(node);
}

How to Thread2 avoid accessing null pointer when executing doSomething(node) but node is delete from thread1 ;

While this can be solved using standard lock mechanism (see mutex), you may want to look into the Reader-Writer specific synchronization primitive. It will allow to have more than one reader, but only one writer can process the list at a time.

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