不改变大小的数组指针。我需要锁吗?

array pointers that don't change size. Do I need locks?

我正在使用线程来提高我的程序的速度。

因此我现在有一个 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);
   }
}

do I need to use mutexes?

不,因为数组是在创建线程之前预先分配的并且不会改变大小,并且每个线程独立地访问数组的不同元素,所以没有重叠或共享任何需要的数据防止跨线程边界的并发访问。

Given that they are accessing and modifying the same bitset array, do I need to use mutexes?

没有;只要每个线程使用数组的单独元素,就不需要同步。

但是,由于 "false sharing" 从多个线程访问同一缓存行导致,如果位集很小,对该数组的访问可能会被有效地序列化。如果线程仅花费少量时间访问数组,例如仅在昂贵计算的最后写入,这将不是问题。

bitset<UINT64_MAX>虽然不小。其中 8 个位集总共是 16 个 Exa 字节。我希望你在采购硬件时能得到一笔好交易:)