In modern Julia, I would probably prefer to use threads for this.
Start julia with julia --threads auto
.
function count_heads(trials)
flips = rand(Bool, trials)
num_heads = sum(flips)
return num_heads
end
trial_counts = [1000, 2000, 3000, 4000]
head_counts = zeros(Int, length(trial_counts))
Threads.@threads for i in eachindex(trial_counts)
head_counts[i] = count_heads(trial_counts[i])
end
println("Trial Counts:", trial_counts)
println("Head Counts:", head_counts)
Executing the code in the Julia REPL outputs the following.
julia> Threads.nthreads()
6
julia> function count_heads(trials)
flips = rand(Bool, trials)
num_heads = sum(flips)
return num_heads
end
count_heads (generic function with 1 method)
julia> trial_counts = [1000, 2000, 3000, 4000]
4-element Vector{Int64}:
1000
2000
3000
4000
julia> head_counts = zeros(Int, length(trial_counts))
4-element Vector{Int64}:
0
0
0
0
julia> Threads.@threads for i in eachindex(trial_counts)
head_counts[i] = count_heads(trial_counts[i])
end
julia> println("Trial Counts:", trial_counts)
Trial Counts:[1000, 2000, 3000, 4000]
julia> println("Head Counts:", head_counts)
Head Counts:[486, 1016, 1489, 2006]
To format code, do the following in this forum.
```julia
function foo()
println("Hello world")
end
```
```julia-repl
julia> foo()
Hello world
```
Note to others, you can use more backticks to escape triple backticks:
````
```julia
function foo()
println("Hello world")
end
```
````