
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.