Solution using taskpool
    
    
     nimble install taskpools
    
    Run

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()
    
    
    
    Run

Reply via email to