Reputation: 688
I did experiments with boost::upgrade_to_unique_lock/unique_lock && boost::shared_lock, scenario is:
1 write thread, where it has boost::unique_lock existing with a boost::shared_mutex, in the thread, I write to a global AClass
3 read thread, each one has boost::shared_lock with the same boost:;shrared_mutex, they have a loop to read the global AClass
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
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