Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix #100 #101

Merged
merged 1 commit into from
Mar 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading