线程更新全局指针时对全局指针的影响
impact on global pointers while threads updating it
我关心的是,当在线程之间访问时,会对全局指针产生什么影响。我的全局指针是线程安全类。从代码中可以看出,当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;
相关文章:
- 全局作用域中函数指针的赋值
- 在具有全局类型def的类中使用成员函数指针
- 在两个.cpp文件之间定义全局类/结构指针
- 对象指针 c++ 的全局向量错误
- 如何为lua_State设置全局C++指针
- 设置全局指针
- 线程更新全局指针时对全局指针的影响
- 全局指针变量如何存储在内存中?
- 初始化为零的全局指针
- 简单的引用变量赋值导致对象的全局指针出现segfault
- 在函数中创建值,然后将指针保存在全局指针数组中的值上
- 全局指针由优化器解析 - 但引用不是 - 为什么
- 全局指针"already defined in"错误
- 非静态全局对象与指向动态对象的全局指针
- DLL中的全局指针
- 使用全局指针在C++中实现红黑树
- c++全局指针被不同的文件共享
- 函数中指向局部变量的全局指针
- 正在分配全局指针的值
- 全局指针和本地指针有什么区别?