0

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;
    }
shizhen
  • 12,251
  • 9
  • 52
  • 88

2 Answers2

0

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> ....

Evg
  • 25,259
  • 5
  • 41
  • 83
-2

The behave is probably undefined, you can refer to this answer regarding the volatile keyword in C++. https://stackoverflow.com/a/72617/10443813 If the volatile keyword is used, before the following line is executed, the old value is used, and after, the new value is used. Otherwise the behave might be compiler or compiling flag dependent.

    ptrCache = ptrNewCache;
KL-Yang
  • 381
  • 4
  • 8
  • Thanks for the feedback, but ptrcache is Class pointer, if Volitile define on the global pointer ptrcache, you cannot access the member functions. compiler will throw below error: error C2662: 'bool THREAD::SomeCache::SearchValue(const std::string &)': cannot convert 'this' pointer from 'volatile THREAD::SomeCache' to 'THREAD::SomeCache &' – rajesh kumar Jan 25 '19 at 06:58
  • 2
    You have a data race here, and `volatile` has nothing to do with preventing it. – Evg Jan 25 '19 at 07:30