c++ - 如何使用 TBB/OpenMP 锁定数组元素

标签 c++ multithreading locking openmp tbb

我有一个由多个线程读/写的非常大的数组。每个线程一次只会读取其中的一个元素,因此锁定整个数组并不是一个好主意。我期待的是类似

// before threads
lock_t Lock[NUM_THREADS]; 

...

// during threads
get_lock(Lock[thread_id], element_id);
array[element_id]+=10; // some operations
release_lock(Lock[thread_id]);

所以我的问题是,设计get_lockrelease_lock的最佳策略是什么?

最佳答案

当使用 OpenMP 时,您可以使用 atomic 构造获得等效的行为:

// during threads
#pragma omp atomic
array[element_id]+=10; // some operations

为了让您了解它的语义,这里是 OpenMP 3.1 标准的摘录:

The atomic construct ensures that a specific storage location is accessed atomically, rather than exposing it to the possibility of multiple, simultaneous reading and writing threads that may result in indeterminate values

另一方面,如果您决定使用英特尔 TBB,您可以查看 atomic template class .

关于c++ - 如何使用 TBB/OpenMP 锁定数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17553282/

相关文章:

c++ - 在 Visual Studio Code 中对 native C++ 进行单元测试

c++ - C++中的所有临时右值吗?

c# - 如何合并 ThreadLocal<T> 中的所有值?

java - 第二个线程没有输出消息

multithreading - Qt : changing the position of a widget quickly in a loop makes it unvisible for the duration of the loop.为什么?

c++ - 是指针数组吗?

file - 如何故意使文件成为 "EBUSY: resource busy or locked"

concurrency - 如何实现过期的非分布式锁?

python - 使用threading模块在python中实现线程

c++ - 从静态链接的 C++ 库中抛出异常是不安全的?