Reputation: 32309
Two (related) questions about concurrent programming in Haskell compared to Java/Scala:
What do Haskeller's use for concurrent data structures? Is there anything analogous to Java's java.util.concurrent.{ConcurrentHashMap, ConcurrentSkipListSet, ..}
. MVar (Map k v)
does not count :). Shared mutable state is evil, but occasionally necessary.
Is there any equivalent to Java's ExecutorService
? AFAIK, Haskell threads (see fork#
, yield#
, etc. in GHC.Exts
) are all scheduled by something built into the RTS. But what if I specifically want to use a fork join pool, or schedule some computations on a thread pool? Being able to put Future
's on specific execution contexts is really handy in Scala, and I don't know how to do that in Haskell.
Upvotes: 2
Views: 1043
Reputation: 62808
An entire book could be written on this topic, so I'll try to touch on just the points you're asking about.
You can use the par
combinator to schedule pure computations to be done at some future point in time. The RTS already implements work-stealing queues for this and already maintains one thread per CPU core for running them. (If you link your program with the appropriate switches.) Note that this won't help one bit for impure code, and won't let you specify which thread or which core the code executes on.
For shared mutable storage, you have two options.
Explicit locking using MVar
. This has all the usual pitfalls of locking in other programming languages. (Deadlocks, forgetting to lock things, locking too many things, locking things too long, not locking them for long enough...) So MVar (Map k v)
absolutely counts!
STM. You seem to misunderstand what this does. The whole point of STM is that you don't need locks. It lets you use shared mutable data structures "as if" they're not shared, but it automatically prevents data races, inconsistent state, and all the other usual problems with not using locks. It also allows a thread to wait on multiple conditions simultaneously. It's an incredible framework!
If you want to run code on a specific OS thread, you're probably looking for forkOS
rather than forkIO
.
Given your use case, I suspect STM is probably what you're looking for. If you have a specific task you're trying to do, post another question and you will probably get more specific advise.
Upvotes: 3