exPools.nim
1 2 import std/[strutils, math, cpuinfo] 3 4 import taskpools 5 6 # From https://github.com/nim-lang/Nim/blob/v1.6.2/tests/parallel/tpi.nim 7 # Leibniz Formula https://en.wikipedia.org/wiki/Leibniz_formula_for_%CF%80 8 proc term(k: int): float = 9 if k mod 2 == 1: 10 -4'f / float(2*k + 1) 11 else: 12 4'f / float(2*k + 1) 13 14 proc piApprox(tp: Taskpool, n: int): float = 15 var pendingFuts = newSeq[FlowVar[float]](n) 16 for k in 0 ..< pendingFuts.len: 17 pendingFuts[k] = tp.spawn term(k) # Schedule a task on the threadpool a return a handle to retrieve the result. 18 for k in 0 ..< pendingFuts.len: 19 result += sync pendingFuts[k] # Block until the result is available. 20 21 proc main() = 22 var n = 1_000 23 var nthreads = countProcessors() 24 25 var tp = Taskpool.new(num_threads = nthreads) # Default to the number of hardware threads. 26 27 echo formatFloat(tp.piApprox(n)) 28 29 tp.syncAll() # Block until all pending tasks are processed (implied in tp.shutdown()) 30 tp.shutdown() 31 32 # Compile with nim c -r -d:release --threads:on --outdir:build example.nim 33 main() 34 35 when false: 36 type 37 ScratchObj_486539477 = object 38 k: int 39 fut: Flowvar[float] 40 41 let scratch_486539455 = cast[ptr ScratchObj_486539477](c_calloc(csize_t 1, 42 csize_t sizeof(ScratchObj_486539477))) 43 if scratch_486539455.isNil: 44 raise newException(OutOfMemDefect, "Could not allocate memory") 45 block: 46 var isoTemp_486539473 = isolate(k) 47 scratch_486539455.k = extract(isoTemp_486539473) 48 var isoTemp_486539475 = isolate(fut) 49 scratch_486539455.fut = extract(isoTemp_486539475) 50 proc taskpool_term_486539478(args: pointer) {.gcsafe, nimcall, 51 raises: [].} = 52 let objTemp_486539472 = cast[ptr ScratchObj_486539477](args) 53 let k_486539474 = objTemp_486539472.k 54 let fut_486539476 = objTemp_486539472.fut 55 taskpool_term(k = k_486539474, fut = fut_486539476) 56 57 proc destroyScratch_486539479(args: pointer) {.gcsafe, nimcall, 58 raises: [].} = 59 let obj_486539480 = cast[ptr ScratchObj_486539477](args) 60 `=destroy`(obj_486539480[]) 61 62 Task(callback: taskpool_term_486539478, args: scratch_486539455, 63 destroy: destroyScratch_486539479)