I remember writing a consumer pattern using 2 threads for consumer and
producer. Using `channel` to send the message, and using `cond` to wait if
there's nothing to consume yet.
import locks
from strutils import parseInt
from os import sleep
when not defined(vcc):
import threadpool
var
chan: Channel[int]
cond: Cond
lock: Lock
time = 700
initLock lock
initCond cond
chan.open
proc chanWaiting() {.thread.} =
while true:
var res = tryRecv chan
if res.dataAvailable:
echo "Get the num: ", res.msg
# to simulate the congestion or slow operation
sleep time
if res.msg > 10:
echo "stopping operation"
break
# immediately for next loop if there's a value to avoid message
# congestion, in the event of there's no message then it will wait
# for the condition signaled
continue
echo "waiting for next iteration"
cond.wait lock
echo "condition signaled"
proc chanSending() {.thread.} =
while true:
var num = try: stdin.readline.parseInt
except: -1
echo "sending ", num
chan.send num
echo "going to signal the condition"
cond.signal
if num > 10:
break
when defined(vcc):
var
threadsend: Thread[void]
threadwait: Thread[void]
threadsend.createThread chanSending
threadwait.createThread chanWaiting
joinThread threadsend
joinThread threadwait
else:
spawn chanWaiting()
spawn chanSending()
sync()
>From what I remembered, signaling condition before the condition waiting will
>make the signal lost. Also, signaling no matter how many are done, condition
>will only be handled once.