-
Notifications
You must be signed in to change notification settings - Fork 3
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
A function to wait for slaves without forking a new thread #4
Comments
What you need is the semaphore idiom. main =
fork $ do
semaphore <- newEmptyMVar
fork $ do
-- Do things
-- ...
-- Release the semaphore
putMVar semaphore ()
-- Block until semaphore is filled with value
takeMVar semaphore For more complicated cases I recommend looking at libraries like "SafeSemaphore". |
I have several forked threads inside |
Probably such a function would be a useful addition. I don't think I'll implement it myself any time soon, however I would accept a PR.
I'm not sure what you're referring here to.
For now you can declare a semaphore per thread (or wrap it in a utility function). Or use a counting semaphore from the mentioned library. |
A utility function could look like this: forkWait :: IO () -> IO (IO ())
forkWait io =
do
semaphore <- newEmptyMVar
fork $ do
io
putMVar semaphore ()
return (takeMVar semaphore) To be used like this: main =
fork $ do
wait1 <-
forkWait $ do
-- Do things
-- ...
wait2 <-
forkWait $ do
-- Do things
-- ...
wait1
wait2 |
slave-thread uses |
It's a different thing. It ensures that the slaves are dead before the finaliser of the master is executed. The slaves still get killed when the master dies. Brutal, I know :) |
@neongreen How about an data Async a
= Async ThreadId (STM a)
async :: IO a -> IO (Async a)
async computation = do
result <- newEmptyTMVarIO
thread <- fork (computation >>= atomically . putTMVar result)
return (Async thread (readTMVar result))
wait :: Async a -> STM a
wait (Async _ computation) = computation
cancel :: Async a -> IO ()
cancel (Async thread _) = killThread thread Note that this still has the |
Oh, but if you just want all slaves to finish, but don't want to keep track of each of them (like with an |
I miss it every time I use slave-thread. I end up doing this:
The text was updated successfully, but these errors were encountered: