JuliaLang / julia

The Julia Programming Language
https://julialang.org/
MIT License
45.82k stars 5.49k forks source link

Race detection #50685

Open themantra108 opened 1 year ago

themantra108 commented 1 year ago

Check for variable used inside function with threaded for loopScreenshot_2023-07-27-03-29-15-041_com.android.chrome-edit.jpg

firedragonironfist commented 1 year ago

Hey, I am interested in working on this issue can you please assign me

gbaraldi commented 1 year ago

You can work on it without being assigned to it ;)

firedragonironfist commented 1 year ago

Ok thanks for letting me know

firedragonironfist commented 1 year ago
using Base.Threads

function unsafe_count()
    counter = zeros(Int, nthreads())  # Initialize a thread-local counter array

    Threads.@threads for _ in 1:10_000
        tid = threadid()  # Get the current thread ID
        counter[tid] += 1  # Increment the thread-local counter
    end

    return sum(counter)  # Sum up the thread-local counters to get the final result
end

result = safe_count()
println(result)
firedragonironfist commented 1 year ago

I have used array here as a local-thread storage that collects individual results from each thread and sums them up at the end

abraemer commented 1 year ago

I am somewhat confused what this issue is about. However the solution of @firedragonironfist is not a good one. Please refer to PSA: Thread-local state is no longer recommended as to why.

In this simple example you could just use Threads.atomic_add! like so

function safe_count()
    counter = Threads.Atomic{Int}(1)
    Threads.@threads for _ in 1:10_000
        Threads.atomic_add!(counter, 1)
    end
end

Generally the discourse is more suited for getting help than opening an issue on Github.

themantra108 commented 1 year ago

Compiler Warning for, when multiple threads changing same variable simultaneously

themantra108 commented 1 year ago

https://go.dev/blog/race-detector