我有一個必須以互斥方式執行的操作。在其他語言中,我可以執行以下操作(類似于 Python 的偽代碼):
with myLock:
# here lock is acquired
do mutual exclusive operation
# here lock is released
當然,我可以在 Haskell 中使用MVar: 來完成它,然后將它放回去。但我想這樣做IORef:
-- somewhere
duringOperation :: IORef Bool
.....
-- operation execution:
mayIStart <- atomicModifyIORef' duringOperation $ \case
-- tuple is treated as (lock/keep-locked, may I start the operation)
True -> (True, False)
False -> (True, True)
if mayIStart then do
-- here I am doing my operation in a mutual exclusive way
...
-- after completion I reset duringOperation flag
atomicWriteIORef' _duringOperation False
else
-- something else...
它看起來像其他語言中的典型“原子”或“同步”標志。但我不確定它在 Haskell 中的安全性以及IORef用于實作此類目標的情況。同樣,我的想法是使用IORef. 真的安全嗎(操作真的會互斥)?
uj5u.com熱心網友回復:
是的,它是安全的。這正是atomicin 的atomicModifyIORef意思。來自精細檔案:
以原子方式修改 IORef 的內容。
此函式對于在多執行緒程式中以安全的方式使用 IORef 很有用。如果你只有一個 IORef,那么使用 atomicModifyIORef 訪問和修改它會防止競爭條件。
我相信您在釋放“互斥鎖”時不需要原子地撰寫,即writeIORef duringOperation False應該沒問題 - 相信操作在不安全時運行,只是效率較低。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/506258.html
標籤:哈斯克尔
