TMREWSync (TMultiReadExclusiveWriteSynchronizer) questions

筅森魡賤 提交于 2021-01-20 09:05:33

问题


I have questions about TMREWSync:

  1. Is it possible to upgrade Read lock to Write lock without unlocking?

  2. Don't understand what I should do if BeginWrite returns false?


回答1:


  1. Yes, TMREWSync supports lock upgrades. Use it like: BeginRead ... BeginWrite ... EndWrite ... EndRead.

  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!