我有一个由多个线程读/写的非常大的数组。每个线程一次只会读取其中的一个元素,因此锁定整个数组并不是一个好主意。我期待的是类似
// 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_lock
和release_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/