1

I was wondering about how to use mutex for multithreaded application. Do my getters need to lock too? I found this post. The answer is yes, I need to guard getters functions but that means I'll be able to perform one read at a time, and I wonder if it could be improved.

T.E.D's answer suggests that you can implement locks in a way that many threads can read the data at the same time if setters' functions didnt lock the mutex to perform a write. I tried to find some examples - reading Qt's documentation - tought, QMutex doesn't have a isLocked() function or something like this. So how can you praticly implements this kind of "intelligent's locks'.

Thanks

Community
  • 1
  • 1
Xaqq
  • 4,308
  • 2
  • 25
  • 38

2 Answers2

5

You need a special kind of locking mechanism called readers-writer lock. With this lock any number of readers can access the resource simultaneously, but for a writer to have access all reader threads must block.

Looks like Qt has a QReadWriteLock class that implements this mechanism.

Miguel Grinberg
  • 65,299
  • 14
  • 133
  • 152
3

Yes, you need to synchronize access to your getters, not to lock them in common sence since they don't modify anything, but to put a memory barrier implicitly. So multithreaded operations will be put in right order and your getters will won't read partially modified data.

You don't need any intelligent locks, because reader-writer mutex won't provide you any benefit.

Community
  • 1
  • 1
Andriy Tylychko
  • 15,967
  • 6
  • 64
  • 112