Search code examples
c++race-conditionstdthread

impact on global pointers while threads updating it


My concerns is, what will be the impact on the global pointers when accessed between the threads. My global pointer were a thread safe class. From the code what will the impact on the global pointer, when updatethread() method updating the pointer with new pointer and workerthread() accessing the pointer. What synchronization i should work with?

SomeCache* ptrCache = NULL;

    //worker thread
    void Workerthread(std::string strFileToWork)
    {
        while (std::getline(fileStream, strCurrent))
        {                   
            //worker thread accessing the global pointer
        if (ptrCache->SearchValue(strCurrent))
        {           
            iCounter++;
        }
        }
    }

    void updatethread()
    {
        //replace old cache with a new fresh updated.
        SomeCache* ptrOldCache = ptrCache;
        ptrCache = ptrNewCache;
    }

Solution

  • One possible solution with mutexes:

    std::mutex ptrCacheMutex;
    SomeCache* ptrCache = null_ptr;
    
    void Workerthread(...)
    {
        ...
        bool valueFound;
        {
            std::scoped_lock lk(ptrCacheMutex);
            valueFound = ptrCache && ptrCache->SearchValue(...);
        }
        if (valueFound)
            iCounter++;
        ...
    }
    
    void updatethread()
    {
        ...
        {
            std::scoped_lock lk(ptrCacheMutex);
            auto ptrOldCache = std::exchange(ptrCache, ptrNewCache);
        }
        ...
    }
    

    If your compiler doesn't support template argument deduction, you should specify mutex type explicitly: std::scoped_lock<std::mutex> ....