install taskpools
my test program:
# fib(47) = 2971215073
# without threads: 5.491s. this program with threads: 0.650s
import
std/cpuinfo,
taskpools
const nthreads = 12 # 6 core system, 12 hyper threads
var tp = Taskpool.new(num_threads = nthreads)
proc fib(n:int) : int =
if n < 2: n
else: fib(n-1) + fib(n-2)
proc fib2(n:int) : int =
var pendingFuts = newSeq[FlowVar[int]](2)
if n > 25:
pendingFuts[0] = tp.spawn fib2(n-1)
pendingFuts[1] = tp.spawn fib2(n-2)
for k in 0..1:
result += sync pendingFuts[k]
else:
result = fib(n)
proc main() =
let n = 47
echo "fib(",n,") = ",fib2(n)
main()
If I compile with
nim2 c -r -d:release --threads:on fib2p.nim
/home/doug/nim-tdt/parallel/fib2p.nim(9, 18) template/generic instantiation of `new` from here
/home/doug/.nimble/pkgs/taskpools-0.0.4/taskpools/taskpools.nim(372, 17) template/generic instantiation of `createThread` from here
/home/doug/Nim/lib/std/typedthreads.nim(241, 50) template/generic instantiation of `threadProcWrapper` from here
/home/doug/Nim/lib/system/threadimpl.nim(106, 27) template/generic instantiation of `threadProcWrapStackFrame` from here
/home/doug/Nim/lib/system/threadimpl.nim(100, 27) template/generic instantiation of `threadProcWrapDispatch` from here
/home/doug/Nim/lib/system/threadimpl.nim(79, 5) Warning: The bare except clause is deprecated; use `except CatchableError:` instead [BareExcept]
/home/doug/.nimble/pkgs/taskpools-0.0.4/taskpools/taskpools.nim(184, 1) Hint: 'new' cannot raise 'AssertionDefect' [XCannotRaiseY]
/home/doug/.nimble/pkgs/taskpools-0.0.4/taskpools/channels_spsc_single.nim(41, 1) Hint: 'initialize' cannot raise 'AssertionDefect' [XCannotRaiseY]
/home/doug/.nimble/pkgs/taskpools-0.0.4/taskpools/channels_spsc_single.nim(68, 1) Hint: 'trySend' cannot raise 'AssertionDefect' [XCannotRaiseY]
stack trace: (most recent call last)
tasks.nim(118, 12) toTask
/home/doug/nim-tdt/parallel/fib2p.nim(19, 24) template/generic instantiation of `spawn` from here
/home/doug/.nimble/pkgs/taskpools-0.0.4/taskpools/taskpools.nim(515, 26) template/generic instantiation of `toTask` from here
/home/doug/.nimble/pkgs/taskpools-0.0.4/taskpools/taskpools.nim(514, 16) Error: 'toTask' takes a GC safe call expression
you need to add {.gcsafe.} to fib2 like this:
proc fib2(n:int):int{.gcsafe.} =