There is a function in the Julia language that fills an array with random values in parallel and calculates its sum:
function thread_test(v)
Threads.@threads for i = 1:length(v)
@inbounds v[i] = rand()
end
sum(v)
end
@inbounds is a macro that disables checks for a possible index out of the array, since in this case the index will always lie within its boundaries.
Why might a race condition occur when executing this code?
CodePudding user response:
rand
is generally not thread-safe in most languages, including some version of Julia. This means calling rand()
from multiple threads can cause an undefined behaviour (in practice, the seed is typically written by different threads at the same time decreasing performance and the randomness of the random number generator). The Julia documentation explicitly states:
In a multi-threaded program, you should generally use different RNG objects from different threads or tasks in order to be thread-safe. However, the default RNG is thread-safe as of Julia 1.3 (using a per-thread RNG up to version 1.6, and per-task thereafter).
Besides this, the code is fine.
CodePudding user response:
Because multiple threads are accessing the same variable (v) at the same time, which can lead to unexpected results.