June 2019
Intermediate to advanced
218 pages
5h 19m
English
Remember the code we saw in Chapter 7, Accelerating Code with the GPU, to calculate the value of pi using Monte Carlo simulation. It used a loop to calculate a position based on draws from a random number generator. It should, therefore, be easy to run this in parallel across many threads.
Let's remind ourselves of the serial code:
using Randomfunction darts_in_circle(n, rng=Random.GLOBAL_RNG) inside = 0 for i in 1:n if rand(rng)^2 + rand(rng)^2 < 1 inside += 1 end end return inside endfunction pi_serial(n) return 4 * darts_in_circle(n) / nend
The simplest way to parallelize this function would be to add a @threads annotation in front of the for loop. However, that would be very wrong. Notice that ...
Read now
Unlock full access