Skip to content

Commit

Permalink
Fix #100 (#101)
Browse files Browse the repository at this point in the history
  • Loading branch information
carstenbauer authored Mar 28, 2024
1 parent 13db599 commit ac96481
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 10 deletions.
19 changes: 9 additions & 10 deletions src/tools.jl
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,8 @@ May be used to mark a region in parallel code to be executed by a single task on
See [`try_enter!`](@ref) and [`reset!`](@ref).
"""
mutable struct OnlyOneRegion
@atomic latch::Bool
OnlyOneRegion() = new(false)
@atomic task::Union{Task, Nothing}
OnlyOneRegion() = new(nothing)
end

"""
Expand Down Expand Up @@ -62,24 +62,23 @@ end
```
"""
function try_enter!(f, s::OnlyOneRegion)
latch = @atomic :monotonic s.latch
if latch
ct = current_task()
t = @atomic :monotonic s.task
if !isnothing(t) && ct != t
return
end
(_, success) = @atomicreplace s.latch false=>true
if !success
return
if ct == t || (@atomicreplace s.task nothing=>ct).success
f()
end
f()
return
end

"""
Reset the `OnlyOneRegion` (so that it can be used again).
"""
function reset!(s::OnlyOneRegion)
@atomicreplace s.latch true=>false
nothing
@atomic s.task = nothing
return
end

"""
Expand Down
16 changes: 16 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -454,6 +454,22 @@ end
catch ErrorException
@test false
end

x = 0
y = 0
try
@tasks for i in 1:10
@set ntasks = 2

y += 1 # not safe (race condition)
@only_one begin
x += 1 # parallel-safe because only a single task will execute this
end
end
@test x == 5 # a single task should have incremented x 5 times
catch ErrorException
@test false
end
end

@testset "@only_one + @one_by_one" begin
Expand Down

0 comments on commit ac96481

Please sign in to comment.