Created
September 1, 2015 03:52
-
-
Save rogercloud/d2ec8ef6d683b5b6804f to your computer and use it in GitHub Desktop.
Warning: use global iterator here is not a good practice.
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
import os, threadpool, macros | |
template spawnBackgroundJob(t: typedesc, chan:ptr TChannel[t], iter: expr): stmt {.immediate.}= | |
block: | |
proc threadFunc(channel: ptr TChannel[t]) {.thread.} = | |
echo "Thread is starting" | |
for i in iter: | |
echo "Sending ", i | |
channel[].send(i) | |
channel[].open() | |
var thread: TThread[ptr TChannel[t]] | |
createThread(thread, threadFunc, chan) | |
#joinThread(thread) | |
# example use in some main thread: | |
iterator testJob(): int = | |
yield 0 | |
sleep(500) | |
yield 1 | |
sleep(500) | |
yield 2 | |
var channel: ptr TChannel[int] | |
channel = cast[ptr TChannel[int]](allocShared0(sizeof(TChannel[int]))) | |
spawnBackgroundJob(type(int), channel, testJob()) | |
for i in 1 .. 10: | |
sleep(200) | |
echo channel[].peek() | |
channel[].close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment