JQ.
JQ.

Reputation: 688

boost::unique_lock/upgrade_to_unique_lock && boost::shared_lock can exist at the same time ? it worries me

I did experiments with boost::upgrade_to_unique_lock/unique_lock && boost::shared_lock, scenario is:

I observed all the threads are holding locks( 1 unique, 3 shared ) at the same time, and they all running data access loops.

my concern is AClass is not thread-safe, if I can do read/write at the same time in different threads, the read could crash. Even it's not AClass, we use primitive types, reading them surely will not crash, but the data could be dirty, isn't it ?

Upvotes: 0

Views: 1104

Answers (1)

James McNellis
James McNellis

Reputation: 355267

boost::shared_lock<boost::shared_mutex>(gmutex);

This is not an "unnamed lock." This creates a temporary shared_lock object which locks gmutex, then that temporary shared_lock object is destroyed, unlocking gmutex. You need to name the object, making it a variable, for example:

boost::shared_lock<boost::shared_mutex> my_awesome_lock(gmutex);

my_awesome_lock will then be destroyed at the end of the block in which it is declared, which is the behavior you want.

Upvotes: 3

Related Questions