views:

3319

answers:

2

I have a multithreaded app that has to read some data often, and occasionally that data is updated. Right now a mutex keeps access to that data safe, but it's expensive because I would like multiple threads to be able to read simultaneously, and only lock them out when an update is needed (the updating thread could wait for the other threads to finish).

I think this is what boost::shared_mutex is supposed to do, but I'm not clear on how to use it, and haven't found a clear example.

Does anyone have a simple example I could use to get started?

+9  A: 

It looks like you would do something like this:

boost::shared_mutex _access;
void reader()
{
  // get shared access
  boost::shared_lock lock(_access);

  // now we have shared access
}

void writer()
{
  // get upgradable access
  boost::upgrade_lock lock(_access);

  // get exclusive access
  boost::upgrade_to_unique_lock uniqueLock(lock);
  // now we have exclusive access
}
1800 INFORMATION
This is my first time using boost, and I'm a C++ newbie, so maybe there's something I'm missing -- but in my own code, I had to specify the type, like so: boost::shared_lock<shared_mutex> lock(_access);
Ken Smith
I'm trying to use this myself but I'm getting an error. missing template arguments before 'lock'. Any ideas?
Matt H
Hi, are those locks scoped or would I need to explicitly release them? TIA
shaz
A: 

1800 INFORMATION's example is correct.

See also this article: What's new in Boost Threads.

Assaf Lavie