Reputation:
I am curious how does a mutex know what data to protect and what data not to protect. I've been using mutexes (mutices?) in Qt, and a QMutex
does not specify any particular members to be locked.
One idea that comes to my head is that the mutex doesn't lock any resource but a routine which works on a resource, and in order for that routine to work the mutex must be unlocked. But that would mean that if I can acquire a pointer to that resource, I can still modify it in another thread that doesn't go through the lockable routine, which would mean it is actually impossible to fully protect an area in memory, it can only be protected if it is only accessible through a single lockable routine. Is that correct?
Upvotes: 7
Views: 2182
Reputation: 781
Yes, you are right. Mutexes guarantee code is accessed by only one thread at a time, not data.
But you can have the data protected by encapsulating it: put the protected resource in private fields and make get/set accessors use the mutex to coordinate access. This kind of "wrapping" is called a Monitor http://en.wikipedia.org/wiki/Monitor_(synchronization) .
Upvotes: 8
Reputation: 56467
That's correct. Mutex only locks a thread. It does not lock a resource. You can still access it via direct memory manipulation. So in that sense it is not safe (but on the other hand nothing can stop you from direct memory manipulation). But you should never do that. That's why layers of abstraction exist.
Upvotes: 5