199207 (3) [Avatar] Offline

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?


anthony.williams (216) [Avatar] Offline
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.