The Author Online Book Forums are Moving

The Author Online Book Forums will soon redirect to Manning's liveBook and liveVideo. All book forum content will migrate to liveBook's discussion forum and all video forum content will migrate to liveVideo. Log in to liveBook or liveVideo with your Manning credentials to join the discussion!

Thank you for your engagement in the AoF over the years! We look forward to offering you a more enhanced forum experience.

199207 (3) [Avatar] Offline
#1
Hi,

In listing 6.11 - A Thread safe lookup table.
It states

Because the number of buckets is fixed, the get_bucket() function #7 can be called without any locking #8, #9, #10

This is fine, but how do we know the initialisation of the vector, and in particular the calls

buckets[i].reset(new bucket_type);

are visible to the other threads when calling #8, #9, #10.

Do you not need to lock the mutex to ensure a synchronization point?

Thanks

CE
anthony.williams (216) [Avatar] Offline
#2
The bucket initialization is done in the constructor. Whatever mechanism you use to ensure that the constructor is complete before the lookup table is accessed will ensure that the buckets vector is correctly initialized.

This may be an external mutex, or any other mechanism to ensure ordering. For example, you could just rely on thread creation providing cross-thread ordering: if you create the table in one thread, then create another thread from there, then the constructed lookup table is fully visible in the new thread.

Whatever data type you use, you always need to ensure that only one thread runs the constructor, and no other thread can access the object until the constructor is complete. Whatever synchronization you use to ensure that will also ensure that the object initialization is properly visible to the subsequent threads that access the data structure.