lundi 14 mai 2018

Any proper way to achieve this?

I have an array of objects that I want to operate on in threads, but I also want to be able to clear and rebuild that array at times. This feels like a hacky way to achieve my goal, but is there a better way to do something like this?:

atomic<int> inThreadCount;
atomic<int> arrayLock;
map<string, myObj> myMap;
mutex mu;
class myObj{
    mutex mu;
    int myInt;
    void update(){
        mu.lock();
        myInt++;
        inThreadCount--;
        mu.unlock();
    }
}
void refreshList(){
    mu.lock();
    arrayLock++;
    while (inThreadCount > 0)
        Sleep(0);
    myMap.clear();
    myMap.insert(make_pair("myObj", new myObj));
    arrayLock--;
    mu.unlock();
}

void updateObject(){
    while (arrayLock > 0)
        Sleep(0);
    inThreadCount++;
    async(std::launch::async, myObj.update());
}

PS, I realize that there is a tiny window of opportunity for error between Sleep() and arrayLock/inThreadCount++. That's part of the problem I want to solve!

Aucun commentaire:

Enregistrer un commentaire