Sign in to follow this  
GuyWithBeard

Multithreading and mutexes

Recommended Posts

GuyWithBeard    1892
Hi!

This might be a stupid question, but it's something that I have wondered about for a while now.

In a multithreaded application, you have a class that has static data members and static functions to modify those static data members. All of the threads can use these functions whenever they want. Now, for the ones that write data I need to protect the data, eg. with a boost scoped mutex (right?). But what about the functions that does not modify the data? Is it safe to read the same place in memory simultaneously from several threads, or do I need to protect the reading code with something like a mutex as well?

Share this post


Link to post
Share on other sites
Slavik81    360
You need to lock read and write access while writing.

If there's a writer, there can be no other readers or writers. If there is no writer, there can be unlimited readers.

Both need to be protected in slightly different ways to satisfy those conditions. I think boost SharedLockable is what you want.

Share this post


Link to post
Share on other sites
ApochPiQ    23065
If you only read, you don't need a lock.

As soon as writes are permitted, regardless of when they may occur, [i]all[/i] accesses (reads [b]and[/b] writes) must be protected.

As Slavik81 notes, however, there exists such a thing as a [i]reader/writer lock[/i] which is specifically designed to handle the case you describe.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this