Created
March 8, 2021 18:22
-
-
Save samdmarshall/79cf2c5d629349e625b2b34756b3e92f to your computer and use it in GitHub Desktop.
This file contains hidden or 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
# ======= | |
# Imports | |
# ======= | |
import json | |
import strformat | |
import asyncdispatch | |
import threadproxy | |
# ===== | |
# Types | |
# ===== | |
type | |
Queue = object | |
name: string | |
token: ThreadToken | |
thread: Thread[QueueTask] | |
QueueTask = object | |
token: ThreadToken | |
QueueManager = object | |
main: MainThreadProxy | |
QueueMain = proc (task: QueueTask) {.thread, nimcall.} | |
# ========= | |
# Functions | |
# ========= | |
# ======= | |
# Threads | |
# ======= | |
proc workerMain(task: QueueTask) {.thread.} = | |
let proxy = newThreadProxy(task.token) | |
# register action handler | |
proxy.onData "multiply": | |
echo "processing task!" | |
let x = data["value"].getInt() | |
return %*{"value": x + 20} | |
# start processing channel | |
waitFor proxy.poll() | |
proc response(f: Future[JsonNode]) = | |
echo "future callback!" | |
let data = f.read() | |
let value = data["value"].getInt() | |
echo fmt"{value - 20} -> {value}" | |
# =========== | |
# Entry Point | |
# =========== | |
proc main() = | |
let proxy = newMainThreadProxy("main") | |
asyncCheck proxy.poll() | |
proxy.onData "stop": | |
proxy.stop() | |
let token = proxy.createToken("thread_1") | |
var worker: Thread[QueueTask] | |
createThread(worker, workerMain, QueueTask(token: token)) | |
let index = 8 | |
# for index in 0..10: | |
let data = %*{"value": index} | |
echo "dispatching task: " & $data | |
let answer = proxy.ask("thread_1", "multiply", data) | |
answer.addCallback response | |
echo "done dispatching" | |
runForever() | |
when isMainModule: | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment