4 ms·
Here's a practical application of mfix: mfix $ \threadId -> forkIO $ do -- computation in forked thread forkIO creates a new thread and returns its
by pka 9y ago
Here's a practical application of mfix:
mfix $ \threadId -> forkIO $ do
-- computation in forked thread
forkIO creates a new thread and returns its thread id. However, in order to access the returned thread id inside the forked computation, normally one would have to store it in a variable and then read from it inside the thread.
mfix, by nature of its laziness, captures the return value of the function passed to it, and passes it to said function.
- conistonwater 9y agoIt's a very neat example, and I like it very much as an illustration of mfix, but wouldn't one just use Control.Concurrent.myThreadId for that? Seems a little overkill.
- pka 9y agoHa, I guess this must be some kind of selective blindness then :) I've seen myThreadId many times, it makes perfect sense, and yet, whenever I've had to grab the spawned thread id I've always reached for mfix... Well, in this particular case there's of course no need for that. But the general pattern applies to many things. One other example that immediately springs to mind is e.g. registering a callback while needing the ability to unregister the callback from within itself, using some sort of id returned from the registering function.