Multi-threading monotonic dynamic

No. This example illustrates it:

using .Threads
lk = ReentrantLock()
disorder = Int[]
@threads for i in 1:20
  @lock lk push!(disorder,i)
end

The content of array disorder is usually not monotonic.

Here’s one way it can be achieved:


iter = Atomic{Int}(1)
order = Int[]
@threads for _ in 1:20
  i = atomic_add!(iter,1)
  @lock lk push!(order, i)
end

(Not that the array order is guaranteed to be monotonic, some thread can be delayed, though often not in this simple example).

1 Like