问题
I have questions about TMREWSync:
Is it possible to upgrade Read lock to Write lock without unlocking?
Don't understand what I should do if BeginWrite returns false?
回答1:
Yes, TMREWSync supports lock upgrades. Use it like:
BeginRead
...BeginWrite
...EndWrite
...EndRead
.Source code in
System.SysUtils
states:
The function result of BeginWrite indicates whether another thread got the write lock while the current thread was waiting for the write lock. Return value of True means that the write lock was acquired without any intervening modifications by other threads. Return value of False means another thread got the write lock while you were waiting, so the resource protected by the MREWS object should be considered modified. Any samples of the protected resource should be discarded.
My suggestion is that you write your algorithm so that it doesn't depend on this return value. The source code agrees with me:
In general, it's better to just always reacquire samples of the protected resource after obtaining a write lock. The boolean result of BeginWrite and the RevisionLevel property help cases where reacquiring the samples is computationally expensive or time consuming.
回答2:
Such upgrade is generally not easy. Consider two reader thread trying to upgrade at the same time. That would be deadlock.
One solution is to make one (and at most one) of readers upgradable from the start, other readres are not. boost::upgrade_mutex
is an example. Other may be that upgrade may fail, and in this case upgrader is requested to release reader lock without retrying. All this is not very much better than just release and re-acquire writer lock.
I believe that most of the time you don't care about BeginWrite
returned value. Most other shared mutex implementations do not return this value.
(I beleive that the question is tagged WinAPI incorrectly. There is SRW Lock, but it is different from TMREWSync)
来源:https://stackoverflow.com/questions/60463076/tmrewsync-tmultireadexclusivewritesynchronizer-questions