Created
February 6, 2022 09:07
-
-
Save ianfun/87f3105a51ed151c4bef55f6712db63c to your computer and use it in GitHub Desktop.
Consumer and Supplier with thread and condition variable in Nim
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# compile nim c --threads:on --hints:off --run main.nim | |
import locks, random | |
from os import sleep | |
var | |
supplier, consumer: Thread[void] | |
repeat = 0 | |
lock: Lock | |
cond: Cond | |
value: uint64 | |
running = true | |
proc Supplier() {.thread, nimcall.} = | |
randomize() | |
var rand = initRand() | |
while running: | |
lock.acquire() | |
value = rand.next | |
echo "\t\t\tSupplier: wake up" | |
cond.signal() | |
inc repeat | |
lock.release() | |
sleep(500) # give Consumer time to acquire lock (mutex) | |
proc Consumer() {.thread, nimcall.} = | |
while true: | |
lock.acquire() | |
if repeat > 10: break | |
wait cond, lock | |
echo "Consumer: receive ", $value | |
lock.release() | |
running = false | |
lock.initLock() | |
cond.initCond() | |
createThread(consumer, Consumer) | |
createThread(supplier, Supplier) | |
joinThread(consumer) | |
joinThread(supplier) | |
echo "Main: exit" | |
lock.deinitLock() | |
cond.deinitCond() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment