简体   繁体   English

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

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

I am using threads to increase the speed of my program. 我正在使用线程来提高程序速度。

As a result I now have a 8 bitset<UINT64_MAX> bitsets. 结果,我现在有一个8位的bitset<UINT64_MAX>集。 I plan on creating 8 separate threads, each of which are responsible for setting and checking the bitset they own, which is defined by an index passed to each thread. 我计划创建8个独立的线程,每个线程负责设置和检查它们拥有的位集,这些位集由传递给每个线程的索引定义。

Given that they are accessing and modifying the same bitset array, do I need to use mutexes? 鉴于他们正在访问和修改相同的位集数组,我是否需要使用互斥锁?

Here is an example of my code: 这是我的代码示例:

#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? 我需要使用互斥锁吗?

No, because the array is pre-allocated before the threads are created and does not change size, and each thread is independently accessing a different element of the array, so there is no overlap or sharing of any data that needs to be protected from concurrent access across thread boundaries. 否,因为在创建线程之前就已预先分配了数组,并且该数组不会更改大小,并且每个线程都独立地访问数组的不同元素,所以没有任何重叠或共享需要保护并发的数据跨线程边界访问。

Given that they are accessing and modifying the same bitset array, do I need to use mutexes? 鉴于他们正在访问和修改相同的位集数组,我是否需要使用互斥锁?

No; 没有; As long as each thread uses separate element of the array, no synchronisation is needed. 只要每个线程使用数组的单独元素,就不需要同步。

However, the access to that array may be effectively serialised if the bitsets are small, due to "false sharing" caused by accessing the same cache line from multiple threads. 但是,由于从多个线程访问同一缓存行而导致的“错误共享”,如果位集很小,则可以有效地序列化对该数组的访问。 This won't be a problem if the threads only spend a small amount of time accessing the array for example only writing at the very end of an expensive calculation. 如果线程仅花费少量时间访问数组(例如仅在昂贵的计算的最后才写),那么这将不是问题。

bitset<UINT64_MAX> isn't small though. bitset<UINT64_MAX>虽然不小。 8 of those bitsets are 16 Exa Bytes in total. 这些位集中的8位共16个Exa字节。 I hope you got a good deal when sourcing the hardware :) 我希望您在采购硬件时能获得很多收益:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM