1
votes

I'm developing a multi-threaded plugin for a single-threaded application (which has a non-thread-safe API).

My current plugin has two threads: the main one which is application's thread and another one which is used for processing data of the main thread. Long story short, the first one creates objects, gives them an ID, inserts them into a map and sometimes even access and delete them (if application says so); the second one is reading data from that map and is altering objects.

My question is: What tehniques can I use in order to make my plugin thread-safe?

1
Is the main thread allowed to delete an object while the worker thread is working on it?japreiss
I'd count reference to access individual objects (if the first thread doesn't alter them) and a mutex to protect the map (insert new items). Count reference is increased for insertion and for second thread access and decreased for deletion and when the second thread finishes its work. When count reference reaches 0, then the object will (auto)delete itself.Liviu
for programs with a strong seperation of responsibilty for threads i like to use a non blocking queue to communicate jobs and resultsJustin Meiners

1 Answers

5
votes

First, you have to identify where race conditions may exist. Then, you will have to use some mechanism to assure that the shared data is accessed in a safe way, hence achieving Thread Safety.

For your particular case, it seems the race condition will be on the shared map and possibly the objects (map's values) it contains as well (if it's possible that both threads attempt to alter the same object simultaneously).

My suggestion is that you use a well tested thread safe map implementation, and then if needed add the extra "protection" for the map's values themselves. This way you ensure the map is always in a consistent state for both threads, and if both threads attempt to modify the same object data (map's values), the data won't be corrupted or left inconsistent.

For the map itself, you can search for "Concurrent Hash Map" or "Atomic Hash Map" data structures for C++ and see if they are of good quality and are available for your compiler/platform. Good examples are Intel's TBB concurrent_hash_map or Facebook's folly AtomicHashMap. They both have advantages and disadvantages and you will have to analyze what's best for your situation.

As for the objects the map contains, you can use plain mutexes (simple, lock, modify data, unlock), atomic operations (trickier, only for simple datatypes) or other method, once more depending on your compiler/platform and speed requirements.

Hope this helps!