In [1]:
versioninfo()
Julia Version 1.3.0
Commit 46ce4d7933 (2019-11-26 06:09 UTC)
Platform Info:
  OS: Linux (x86_64-pc-linux-gnu)
  CPU: Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
  WORD_SIZE: 64
  LIBM: libopenlibm
  LLVM: libLLVM-6.0.1 (ORCJIT, skylake)
Environment:
  JULIA_NUM_THREADS = 4
In [2]:
Threads.nthreads()
Out[2]:
4
In [3]:
function fib_naive(n)
    if n  1
        n
    else
        fib_naive(n - 2) + fib_naive(n - 1)
    end
end
Out[3]:
fib_naive (generic function with 1 method)
In [4]:
fib_naive(10)
Out[4]:
55
In [5]:
@time fib_naive(40)
  0.726073 seconds (5 allocations: 176 bytes)
Out[5]:
102334155
In [6]:
fib_request(n; spawn=true) = Channel{Int}(spawn=spawn) do channel
    put!(channel, fib_naive(n))
end
Out[6]:
fib_request (generic function with 1 method)
In [7]:
future = fib_request(40)
Out[7]:
Channel{Int64}(sz_max:0,sz_curr:0)
In [8]:
take!(future)
Out[8]:
102334155
In [9]:
function main(nrequests, nfib=40)
    requests = [fib_request(nfib) for _=1:nrequests]
    [take!(req) for req in requests]
end
Out[9]:
main (generic function with 2 methods)
In [10]:
main(4)
Out[10]:
4-element Array{Int64,1}:
 102334155
 102334155
 102334155
 102334155
In [11]:
@time main(4)
  0.784660 seconds (148 allocations: 7.969 KiB)
Out[11]:
4-element Array{Int64,1}:
 102334155
 102334155
 102334155
 102334155
In [12]:
function main2(nrequests, nfib=40)
    requests = [fib_request(nfib, spawn=false) for _=1:nrequests]
    [take!(req) for req in requests]
end
Out[12]:
main2 (generic function with 2 methods)
In [13]:
main2(4)
Out[13]:
4-element Array{Int64,1}:
 102334155
 102334155
 102334155
 102334155
In [14]:
@time main2(4)
  2.925072 seconds (140 allocations: 7.813 KiB)
Out[14]:
4-element Array{Int64,1}:
 102334155
 102334155
 102334155
 102334155
In [ ]: