如何在Haskell中创建关键部分?

Pau*_*-AG 2 haskell

我有多个“线程”,它们与一起运行forkIO。而且我需要处理相互访问,这是典型的关键部分/锁,因为它们将共享相同的内容Map:其中一些将对其进行修改,另一些将对其进行读取。Haskell中使用forkIOAPI,模块,库创建线程的关键部分是什么?

编辑:和所有这一切下 Scotty

Li-*_*Xia 6

Haskell中用于并发的goto库是stm。除了锁定外,Map还可以在原子事务中组织对共享内存(您的shared )的操作。

  • @ Li-yaoXia当然可以,但是只有当您有多个需要保持同步的共享变量时,STM才看起来不错。否则,您将为性能付出任何代价。如果只是缓存,那么“ IORef”(或者也许是“ MVar”)似乎是一个更好的选择。 (3认同)

n. *_* m. 5

AnMVar是一个可变变量,它是它自己的临界区。

\n\n
takeMVar :: MVar a -> IO a \n-- Return the contents of the MVar. If the MVar is currently empty, takeMVar will\n-- wait until it is full. After a takeMVar, the MVar is left empty.\n\nputMVar :: MVar a -> a -> IO ()\n-- Put a value into an MVar. If the MVar is currently full, putMVar will\n-- wait until it becomes empty.\n
Run Code Online (Sandbox Code Playgroud)\n\n

takeMVar\xe2\x80\x94update\xe2\x80\x94putMVarMVar YourMapType基本上就是您所需要的,除非有特定要求,即地图在更新时应以某种方式可用。在这种情况下,您可以用作MVar ()互斥锁来控制对您想要的任何内容的访问。

\n