Mutex in getter setter
I was wondering abou开发者_Go百科t 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
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.
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.
精彩评论