gpt4 book ai didi

haskell - 我可以通过这种方式将 IORef 用作 "mutex"吗?

转载 作者:行者123 更新时间:2023-12-02 01:29:20 25 4
gpt4 key购买 nike

我有一个必须以互斥方式执行的操作。在其他语言中,我可以做类似的事情(类似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 来实现。真的安全吗(操作真的会互斥)吗?

最佳答案

是的,很安全。这正是 atomicModifyIORef 中的 atomic 的含义。来自精美文档:

Atomically modifies the contents of an IORef.

This function is useful for using IORef in a safe way in a multithreaded program. If you only have one IORef, then using atomicModifyIORef to access and modify it will prevent race conditions.

我相信您在释放“互斥体”时不需要以原子方式写入,即 writeIORef whileOperation False 应该没问题 - 相信操作在不运行时正在运行是安全的,只是效率较低。

关于haskell - 我可以通过这种方式将 IORef 用作 "mutex"吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73677784/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com