Boost logo

Threads-Devel :

Subject: Re: [Threads-devel] shared_mutex strategy
From: Jérémy Coulon (jeremy.coulon_at_[hidden])
Date: 2010-05-24 11:14:44


Yes you're right !
Thanks.

Jeremy

Le 24/05/2010 14:01, Anthony Williams a écrit :
> 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


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