mutable boost::mutex is it possible to separate lo

2019-08-13 00:11发布

问题:

So I have functions like read that can be called at the same time from multiple threads. but also I have a function to write that needs to lock all that read functions. Where to get example of creating such archetecture?

I get that we can have:

mutable boost::mutex the_read_mutex;
mutable boost::mutex the_write_mutex;

and:

void write()
{
    // make all new readers wait and wait for all other currently running read threads();
}

void read()
{
    // do not make all new readers wait, and wait for all currently running write thread()
}

So how to do such thing?

回答1:

You can use

boost::shared_mutex  m

Reader()
 shared_lock   lock(m)

Writer()
 upgradeable_lock lck(m)
 upgrade_to_unique_lock uniqueLock(lck);

To know more about boost-locks : Boost thread sync mechanisms

To know about the class of the problem you are dealing with : Wikpedia Link to Reader-WriterLock

To know more about POSIX reader-writer lock, which directly gives you reader write lock with much simple syntax : POSIX reader-witer locks