Boost logo

Boost Users :

Subject: Re: [Boost-users] Several novice questions concerning threading
From: Rob Desbois (rob.desbois_at_[hidden])
Date: 2012-04-12 06:14:37


On 12 April 2012 10:24, Master <master.huricane_at_[hidden]> wrote:

> i modified an example <http://en.highscore.de/cpp/boost/>, but i dont
> know why it gets locked!
>
>> #define BOOST_THREAD_USE_LIB
>> #include <iostream>
>> #include <boost/thread.hpp>
>> #include <vector>
>> using namespace std;
>>
>> vector<int> someSharedResource;
>> boost::mutex mutex;
>> boost::condition_variable_any condition;
>> void Writer()
>> {
>>
>>
>> for (int i = 0; i < 10 ; i++)
>> {
>> boost::unique_lock<boost::mutex> locker(mutex);
>> someSharedResource.push_back(i);
>> // cout<<boost::this_thread::get_id()<<"\t"<<endl;
>> condition.notify_all();
>> condition.wait(mutex);
>> }
>>
>> }
>> void Reader()
>> {
>> int counted_items=0;
>> for( int i =0;i<10;i++)
>> {
>> boost::unique_lock<boost::mutex> locker(mutex);
>> condition.wait(mutex);
>>
>> cout<<someSharedResource.back()<<"\t"<<boost::this_thread::get_id()<<endl;
>> counted_items++;
>> condition.notify_all();
>> }
>>
>>
>> }
>> int main()
>> {
>> boost::thread t1(Writer);
>> boost::thread t2(Reader);
>> t1.join();
>> t2.join();
>> }
>>
> is it not that , the mutex is not released until the writer function ,
> gets passed the wait(mutex) method ? and after that waits for the mutex ?
> and inside reader function , when it is awakened by the notify_all()
> method by writer function , it waits until writer releases the mutex and
> then it owns it and there it executes .
> so why do i fell into a locked down of some kind .
> if i run this example couple of times , some times it works fine and some
> times it just hangs at the beginning ( getting locked ? ) whats wrong with
> it . ?
>

On first iteration:
* Writer gains the lock
* Reader is blocked while trying to obtain lock
* Writer calls condition.notify_all()
* Writer calls condition.wait(), thus releasing the mutex and blocking
itself until condition.notify_*()
* Reader is unblocked
* Reader calls condition.wait(), releasing the mutex and blocking
itself until condition.notify_*()

:-)
--rob

-- 
Rob Desbois
http://theotherbranch.wordpress.com/
"I disapprove of what you say, but I’ll defend to the death your right to
say it", Voltaire


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net