Boost logo

Threads-Devel :

Subject: Re: [Threads-devel] shared_mutex strategy
From: Anthony Williams (anthony_at_[hidden])
Date: 2010-05-24 08:01:13


On 24/05/10 12:10, Jérémy Coulon wrote:
> Hi,
>
> Please consider the following piece of code :
>
> #include <boost/thread/thread.hpp>
>
> #include <boost/thread/mutex.hpp>
>
> #include <iostream>
>
> boost::shared_mutex mux;
>
> boost::mutex io_mux;
>
> void msg(const char *str)
>
> {
>
> boost::mutex::scoped_lock l(io_mux);
>
> std::cout << str << std::endl;
>
> }//msg
>
> void share()
>
> {
>
> mux.lock_shared();
>
> msg("shared - lock_shared acquired");
>
> boost::this_thread::sleep(boost::posix_time::seconds(5));
>
> msg("shared - unlocking shared");
>
> mux.unlock_shared();
>
> }//share
>
> void unique()
>
> {
>
> msg("unique - try_lock");
>
> while (!mux.try_lock())
>
> {
>
> boost::this_thread::sleep(boost::posix_time::seconds(1));
>
> msg("unique - try_lock");
>
> }//while
>
> msg("unique - acquired, unlocking");
>
> mux.unlock();
>
> }//unique
>
> int main()
>
> {
>
> boost::thread_group tg;
>
> tg.create_thread(share);
>
> boost::this_thread::sleep(boost::posix_time::seconds(2));
>
> tg.create_thread(unique);
>
> boost::this_thread::sleep(boost::posix_time::seconds(2));
>
> tg.create_thread(share);
>
> tg.join_all();
>
> return 0;
>
> }//main
>
>
>
> The result is :
> shared - lock_shared acquired
> unique - try_lock
> unique - try_lock
> shared - lock_shared acquired
> unique - try_lock
> shared - unlocking shared
> unique - try_lock
> unique - try_lock
> unique - try_lock
> unique - try_lock
> shared - unlocking shared
> unique - try_lock
> unique - acquired, unlocking
>
>
> So, in that situation, I think the writer is starving !
> Do you agree ?

If you never call a blocking lock() then the scheduling algorithm
(whatever it is) will not take into account the waiting writer. Yes, the
writer starves, but only because you've not asked it to wait.

Anthony

-- 
Author of C++ Concurrency in Action     http://www.stdthread.co.uk/book/
just::thread C++0x thread library             http://www.stdthread.co.uk
Just Software Solutions Ltd       http://www.justsoftwaresolutions.co.uk
15 Carrallack Mews, St Just, Cornwall, TR19 7UL, UK. Company No. 5478976

Threads-Devel list run by bdawes at acm.org, david.abrahams at rcn.com, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk