Open themantra108 opened 1 year ago
Hey, I am interested in working on this issue can you please assign me
You can work on it without being assigned to it ;)
Ok thanks for letting me know
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)
I have used array here as a local-thread storage that collects individual results from each thread and sums them up at the end
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.
Compiler Warning for, when multiple threads changing same variable simultaneously
Check for variable used inside function with threaded for loop