线程更新全局指针时对全局指针的影响

impact on global pointers while threads updating it

本文关键字:全局 指针 影响 线程 更新      更新时间:2023-10-16

我关心的是,当在线程之间访问时,会对全局指针产生什么影响。我的全局指针是线程安全类。从代码中可以看出,当updatethread()方法用新指针更新指针,workerthread()访问指针时,会对全局指针产生什么影响。我应该使用什么同步?

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;
}

一种可能的mutex解决方案:

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);
}
...
}

如果编译器不支持模板参数推导,则应该显式指定互斥类型:std::scoped_lock<std::mutex> ...

Behavior可能未定义,您可以参考C++中关于volatile关键字的答案。https://stackoverflow.com/a/72617/10443813如果使用volatile关键字,则在执行下一行之前,将使用旧值,之后,将使用新值。否则,行为可能依赖于编译器或编译标志。

ptrCache = ptrNewCache;