Incorrect output when using Base.Threads

Picking up on what @foobar_lv2 said. If GFC and GHT modify some of their inputs, then different threads interfere with each other. In your example the loop you want to parallelize only runs 3 times but I assume in reality it will be much more.

The easiest thing to remedy the race condition is to split the workload into chunks and preallocate the things that will be mutated for each chunk. This can be done quite conveniently with ChunkSplitters.jl. Here is the outline:

using ChunkSplitters
function calc()
    # define the variables, do precomputations, allocate output arrays

    ################## Nested Loop Over Time ###################################
    nchunks = Threads.nthreads() # define number of chunks e.g. equal to number of threads
    # @sync tells Julia to wait for any tasks started inside it
    @sync for (xrange, ichunk) in chunks(range(1,dd), nchunks)
        # xrange are the indices this chunk contains, ichunk is just the index of the chunk, which we don't need in this scenario
        Threads.@spawn begin # this line tells Julia to start a new thread with the contents of the begin block
            # now preallocate the workspaces here
            for i in xrange
                # rest of code for the computation
                # ...
                
            end # loop
        end # thread work load
    end # loop over chunks, Julia will wait until all task are completed
end
1 Like