0

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);
   }
}
Terence Chow
  • 10,755
  • 24
  • 78
  • 141
  • https://stackoverflow.com/a/39014404/1043824 Apparently tou have to use some synvhronization mechanism. – inquisitive Jan 30 '19 at 01:16
  • @inquisitive that seems to be referring to operating on a single `bitset` from multiple threads (not a good idea). The question here is about an array of `bitsets` with one `bitset` assigned to each thread and not operated on by any other thread (don't see a problem with this). – user4581301 Jan 30 '19 at 01:20

2 Answers2

3

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.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
1

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 :)

eerorika
  • 232,697
  • 12
  • 197
  • 326