Boost logo

Boost :

Subject: Re: [boost] How to implement a reader-writer lock with quick response to writer?
From: cg (chengang31_at_[hidden])
Date: 2008-09-19 03:38:23


Bill David wrote:
> Question:
> How to implement a reader-writer lock with quick response to writer?
>
[...]
>
> void read() {
> while (true) {
> rw_mutex.lock_shared();
> cout << g_i << endl;
> sleep(3);
> rw_mutex.unlock_shared();
> }
> }
>

The method you used is just fine, but you should release/unlock the
resources as soon as possible, so it would be better if changes the
code to:

void read() {
     while (true) {
         rw_mutex.lock_shared();
         cout << g_i << endl;
        // sleep(3); // <== don't do lengthy job inside the lock
         rw_mutex.unlock_shared();
         sleep(3); // <== move lengthy job which doesn't required
                        // shared resources outside lock
     }
  }

> int main() {
> boost::thread_group threads;
>
> for (int i = 0; i < 3; i++)
> threads.create_thread(read);
>
> sleep(1);
>
> rw_mutex.lock();
> cout << "lock" << endl;
> g_i = 2;
> cout << "update g_i to " << g_i << endl;
> sleep(5);
> cout << "unlock" << endl;
> rw_mutex.unlock();
>
> threads.join_all();
> }
>
> The problem to above solution is it can't respond to writer thread as soon
> as possible, and only in rare case, it can respond to writer thread in about
> 6 seconds.

That is exactly the time of two sleeps which read() takes, during second
sleep, the write requires resource but in vain, so it has to wait to the
read()'s
second sleep finishes.


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk