Problem:
I have std::map of objects called resources. A resource is an object which supports set/get operations of the members inside resource. A set OR get operation also does many other things which are performance heavy. I also need to support an operation to delete a resource from map itself. So there is a possibility when there is a set/get operation is going on resource object. A Resource itself gets deleted and it would cause memory corruption. The Delete resource operation is very infrequent. once in billion.
I have tried to use pthread read-write locks to achieve the thread consistency, but it has a performance impact. Later I tried atomics to solve this problem. here is the code.
std::atomic<bool> g_changeInProgress{false}; // used to block all reader threads
std::atomic<int> g_readers{0}; // used to block delete thread
READER threads
LOOP:
while(g_changeInProgress) {
std::this_thread::yield(); // give opportunity to schedule to other threads
}
g_readers++;
if(g_changeInProgress) {
g_readers--;
goto LOOP;
}
// DO SET/GET opration with the resource
// this portion should not execute in parallel to delete
g_readers--;
Delete thread
g_changeInProgress = true;
while(g_readers) {} // busy loop untill no readers left
/* Delete the Resource here */
g_changeInProgress = false;
This code snippet seems to work fine for me and much faster than pthread read-write locks. Question: In Delete thread is there any possibility compiler can reorder the instruction that would make this code to fail terribly?
Any lighter atomic lock implementation is possible than this?
Aucun commentaire:
Enregistrer un commentaire