简体   繁体   中英

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. 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.

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. 8 of those bitsets are 16 Exa Bytes in total. I hope you got a good deal when sourcing the hardware :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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