Metered concurrency: Difference between revisions

Content deleted Content added
m Fixed lang tags.
Line 322: Line 322:
work(i, 2000, semaphore, timer, println)
work(i, 2000, semaphore, timer, println)
}</lang>
}</lang>

=={{header|Haskell}}==
The QSem (quantity semaphore) waitQSem and signalQSem functions are the Haskell acquire and release equivalents, and the MVar (synchronizing variable) functions are used to put the workers statuses on the main thread for printing. Note that this code is likely only compatible with GHC due to the use of "threadDelay" from Control.Concurrent.

<lang Haskell>import Control.Concurrent
import Control.Monad

worker :: QSem -> MVar String -> Int -> IO ()
worker q m n = do
waitQSem q
putMVar m $ "Worker " ++ show n ++ " has acquired the lock."
threadDelay 2000000 -- microseconds!
signalQSem q
putMVar m $ "Worker " ++ show n ++ " has released the lock."

main :: IO ()
main = do
q <- newQSem 3
m <- newEmptyMVar
let workers = 5
prints = 2 * workers
mapM_ (forkIO . worker q m) [1..workers]
replicateM_ prints $ takeMVar m >>= print</lang>


=={{header|Java}}==
=={{header|Java}}==