As a learning exercise in parallel computing, I would like to parallel compute 
the classic definition of the Fibonacci sequence. I realize there are many fast 
ways to compute the Fibonacci sequence, but I would like to use the classical 
definition as an exercise.

If I try
    
    
    import threadpool
    {.experimental: "parallel".}
    
    proc fib(n:int) : int =
      if n < 2: n
      else: fib(n-1) + fib(n-2)
    
    proc fib2(n:int) : int =
      var n1,n2: int
      
      if n > 20:
        parallel:
          n1 = spawn fib(n-1)
          n2 = spawn fib(n-2)
        n1 + n2
      else:
        fib(n)
    
    proc main() =
      echo "fib(47) = ", fib2(47)
    
    main()
    
    
    Run

then I run 2 threads and reduce the elapsed time about half. If I try more 
threads:
    
    
       n1 = spawn fib2(n-1)
       n2 = spawn fib2(n-2)
    
    
    Run

then I get incorrect answers or endless loops.

OCaml 5.0.0 user manual: "Domainslib provides an async/await mechanism for 
spawning parallel tasks and awaiting their results". In the OCaml user manual 
there is a Fibonacci parallel example that on my 6 core system provides a speed 
up of 7 times using 12 threads.

Is there some similar in nim 1.6 or 2.0 RC 1?

Reply via email to