File: tthread_generic.nim

package info (click to toggle)
nim 2.2.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 1,911,644 kB
  • sloc: sh: 24,603; ansic: 1,761; python: 1,492; makefile: 1,013; sql: 298; asm: 141; xml: 13
file content (39 lines) | stat: -rw-r--r-- 925 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
discard """
  matrix: "--mm:refc; --mm:orc"
  action: compile
"""

type
  ThreadFuncArgs[T] = object of RootObj
    a: proc(): T {.thread.}
    b: proc(val: T) {.thread.}

proc handleThreadFunc(arg: ThreadFuncArgs[int]){.thread.} =
  var fn = arg.a
  var callback = arg.b
  var output = fn()
  callback(output)

proc `@||->`*[T](fn: proc(): T {.thread.},
                 callback: proc(val: T){.thread.}): Thread[ThreadFuncArgs[T]] =
  var thr: Thread[ThreadFuncArgs[T]]
  var args: ThreadFuncArgs[T]
  args.a = fn
  args.b = callback
  createThread(thr, handleThreadFunc, args)
  return thr

proc `||->`*[T](fn: proc(): T{.thread.}, callback: proc(val: T){.thread.}) =
  discard fn @||-> callback

when true:
  import os
  proc testFunc(): int {.thread.} =
    return 1
  proc callbackFunc(val: int) {.thread.} =
    echo($(val))

  var thr = (testFunc @||-> callbackFunc)
  echo("test")
  joinThread(thr)
  os.sleep(3000)