• Advertisement
Sign in to follow this  

Multithreading and mutexes

This topic is 2381 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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
Advertisement
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
If you only read, you don't need a lock.

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

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

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement