简体   繁体   English

何时/为什么在TVar上使用MVar

[英]When/why use an MVar over a TVar

I find TVar's quite easy to work with even though MVar's appear a little simpler, while TVar's a little more featureful. 我觉得TVar很容易使用,即使MVar看起来更简单一些,而TVar更有特色。

So my question is pretty simple, what condition do I want to go to MVar rather than TVar? 所以我的问题很简单,我想要什么条件去MVar而不是TVar? I suppose anytime I don't need transactional update I can use an MVar, but in what way does that benefit me? 我想任何时候我都不需要事务更新我可以使用一个MVar,但这对我有什么好处?

MVar 无功

  • can be empty 可以是空的
  • used to implement synchronization patterns between threads 用于实现线程之间的同步模式
  • allows one-way communication between threads 允许线程之间的单向通信
  • can be faster than TVar in some cases 在某些情况下,可能比TVar更快

TVar 的TVar

  • can not be empty 不能为空
  • atomic transactions 原子交易
  • "shared memory" between threads; 线程之间的“共享内存”; can be used to implement, for example, a lookup cache from which multiple threads can read/write 例如,可以用于实现多个线程可以读/写的查找缓存
  • access is linear time in the number of operations in the transaction log access是事务日志中操作数的线性时间
  • long running transactions are vulnerable to starvation if there are many shorter transactions, preventing them from commiting successfully 如果存在许多较短的事务,则长时间运行的事务很容易受到饥饿,从而阻止它们成功提交

IORef IOREF

  • mutable pointer-like reference 可变指针式引用
  • often used for destructive IO writes/updates 通常用于破坏性IO写入/更新
  • has atomic CAS operations, but complex transactional logic is better suited to a TVar 具有原子CAS操作,但复杂的事务逻辑更适合于TVar

There is not really a hard and fast rule for when to use MVar or TVar . 什么时候使用MVarTVar并没有真正的硬性规则。 If the resource I'm guarding will ever be "missing" (as opposed to empty, consider Nothing vs Just mempty ), then MVar often makes the most sense. 如果我正在守卫的资源将“失踪”(而不是空,请考虑Nothing vs Just mempty ),那么MVar通常是最有意义的。 If I will need to perform atomic blocks of modifications to the resource, then TVar is most suitable. 如果我需要对资源执行原子块修改,那么TVar是最合适的。

TVars are safer but slower. 电视更安全但速度更慢。

MVars can deadlock, but are much, much more efficient. MVars可以死锁,但效率更高。

More efficient still is IORef and atomicModifyIORef (CAS), but that's highly restricted in what you can do with it. 更高效的仍然是IORefatomicModifyIORef (CAS),但是你可以用它来做很多限制。

It's really a safety over performance trade off. 这实际上是对性能权衡的安全性。 TVars are fully general, very safe. TVars非常通用,非常安全。 Everything else is less so, on a decreasing scale. 其他一切都不那么严重,规模越来越小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM