【发布时间】:2023-03-07 01:58:02
【问题描述】:
我正在使用线程来提高程序的速度。
因此,我现在有 8 个bitset<UINT64_MAX> 位集。我计划创建 8 个单独的线程,每个线程负责设置和检查它们拥有的 bitset,这是由传递给每个线程的索引定义的。
鉴于他们正在访问和修改同一个位集数组,我是否需要使用互斥锁?
这是我的代码示例:
#define NUM_CORES 8
class MyBitsetClass {
public:
bitset<UINT64_MAX> bitsets[NUM_CORES];
thread threads[NUM_CORES];
void init() {
for (uint8_t i = 0; i < NUM_CORES; i++) {
threads[i] = thread(&MyBitsetClass::thread_handler, this, i);
}
... do other stuff
}
void thread_handler(uint8_t i){
// 2 threads are never passed the same i value so they are always
// modifying their 'own' bitset. do I need a mutex?
bitsets[i].set(some_index);
}
}
【问题讨论】:
-
stackoverflow.com/a/39014404/1043824 显然你必须使用一些同步机制。
-
@inquisitive 似乎是指从多个线程对单个
bitset进行操作(不是一个好主意)。这里的问题是关于bitsets的数组,其中一个bitset分配给每个线程并且没有被任何其他线程操作(看不出有什么问题)。
标签: c++ concurrency mutex