Home > Enterprise >  When is `Data.Unique` thread safe?
When is `Data.Unique` thread safe?

Time:12-29

The internal implementation of Data.Unique uses IORef as the counter that stores the next unique integer.

From what I know, IORefs are not entirely thread-safe. Especially, in this case, we need to atomically take the data out and add one to it. If it is not atomic we may end up with two same numbers being read before the counter is updated.

I am aware that the implementation of newUnique uses atomicModifyIORef, which is said to be atomic only when one IORef is used in the whole program.

Therefore I can infer that Unique would be thread safe if I do not use any IORefs in my program. The question is: what may happen when I use another IORef? How will the behavior be problematic? Or it will become problematic only if I attempt to use atomicModifyIORef on other IORefs?

CodePudding user response:

The atomicModifyIORef documentation you link reads:

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.

Extending the atomicity to multiple IORefs is problematic, so it is recommended that if you need to do anything more complicated then using MVar instead is a good idea.

This is not saying that it will be unsafe if your program contains multiple IORefs. It's saying that you can't run a single atomic transaction over multiple IORefs. Since Data.Unique only cares about one IORef at a time, never multiple IORefs' relations to each other, there is no race condition from using Data.Unique in conjunction with other IORefs.

  • Related