Skip to content

Instantly share code, notes, and snippets.

@ianfun
Created February 6, 2022 09:07
Show Gist options
  • Save ianfun/87f3105a51ed151c4bef55f6712db63c to your computer and use it in GitHub Desktop.
Save ianfun/87f3105a51ed151c4bef55f6712db63c to your computer and use it in GitHub Desktop.
Consumer and Supplier with thread and condition variable in Nim
# 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