Repository navigation
Description
Summary
When a process may run on only one CPU (for example taskset -c 2, a batch job with one CPU, or a one-CPU cpuset), every cooperative_wait that falls through to a worker thread takes about 7 ms, whatever the operation takes. For AMDGPU.jl, AMDGPU.synchronize() after a 0.2 ms kernel takes 6.98 ms instead of 0.19 ms. Waits short enough to finish within the polling budget are not affected, and the problem goes away with a second CPU.
The cause looks like the lock-holder preemption that #27 fixed for completion callbacks. The worker path still uses Base.Event. notify wakes the other thread while it holds the spin lock inside the event's ReentrantLock. The woken thread then preempts the notifier on the only CPU and spins on that lock until the scheduler's time slice runs out. This happens twice per wait: once when the caller hands the request to the worker, and once when the worker signals that the wait is done.
Related reports
JuliaGPU/CUDA.jl#3060 reports the same symptom with CUDA.jl: nonblocking synchronization is much slower when the process has one CPU (SLURM with one CPU per task, or pinned threads), @time shows lock conflicts in synchronize, and blocking synchronization or a second CPU removes it. carstenbauer/ThreadPinning.jl#115 explains why the worker threads inherit the caller's affinity mask. CUDA.jl now waits through cooperative_wait too, and the last comment on #3060 (CUDACore 6.5.1) still shows the slowdown on one logical CPU. The analysis below points to the cause inside cooperative_wait's worker handoff, so this may also resolve #3060.
Reproducer
Without a GPU, with GPUToolbox only:
# Run: taskset -c 2 julia -t 1 C-nogpu.jl and taskset -c 2,3 julia -t 1 C-nogpu.jl
using GPUToolbox
wait200(_) = (@gcsafe_ccall usleep(200::Cuint)::Cint; nothing)
function median_us(f, reps = 300)
t = map(_ -> (t0 = time_ns(); f(); (time_ns() - t0) / 1e3), 1:reps)
return round(sort(t)[cld(reps, 2)]; digits = 1)
end
median_us(() -> cooperative_wait(wait200, nothing), 10) # compile, start the worker
println(strip(read(`taskset -cp $(getpid())`, String)), ", Julia threads: ", Threads.nthreads())
println("median (µs): cooperative_wait ", median_us(() -> cooperative_wait(wait200, nothing)),
", direct call ", median_us(() -> wait200(nothing)))With AMDGPU.jl, the real-world case:
# Run: taskset -c 2 julia -t 1 C.jl and taskset -c 2,3 julia -t 1 C.jl
using AMDGPU
function busy!(a, n)
i = workitemIdx().x + (workgroupIdx().x - 1) * workgroupDim().x
x = a[i]
for _ in 1:n
x = x * 1.0000001f0 + 1.0f-7
end
a[i] = x
return
end
function median_wait_us(a, blocking; n = 20_000, reps = 200)
t = map(1:reps) do _
@roc groupsize = 256 gridsize = 16 busy!(a, n)
t0 = time_ns()
AMDGPU.synchronize(; blocking)
(time_ns() - t0) / 1e3
end
return round(sort(t)[cld(reps, 2)]; digits = 1)
end
a = AMDGPU.zeros(Float32, 4096)
median_wait_us(a, false; reps = 10); median_wait_us(a, true; reps = 10) # compile
println(strip(read(`taskset -cp $(getpid())`, String)), ", Julia threads: ", Threads.nthreads())
println("median wait (µs): blocking=false ", median_wait_us(a, false),
", blocking=true ", median_wait_us(a, true))Output
GPU-free reproducer (in my runs GPUToolbox was loaded as AMDGPU's dependency, so the HIP runtime was loaded but idle):
pid ...'s current affinity list: 12, Julia threads: 1
median (µs): cooperative_wait 7999.7, direct call 251.8
pid ...'s current affinity list: 12,13, Julia threads: 1
median (µs): cooperative_wait 255.2, direct call 251.8
AMDGPU reproducer:
pid ...'s current affinity list: 12, Julia threads: 1
median wait (µs): blocking=false 6976.2, blocking=true 192.8
pid ...'s current affinity list: 12,13, Julia threads: 1
median wait (µs): blocking=false 193.6, blocking=true 192.6
A repeat run on one CPU gave 6980.0 and 192.5.
Environment
- AMD Ryzen AI MAX+ 395 (16 cores, 32 threads), integrated Radeon 8060S (gfx1151), 64 GiB shared memory
- Ubuntu 24.04.5, Linux 7.0.0 (generic,
PREEMPT_DYNAMIC,CONFIG_HZ=1000). The default EEVDF slice, read from/proc/self/sched(se.slice), is 2.8 ms. - Julia 1.13.4, 1 default thread, 0 interactive threads, 1 GC thread
- GPUToolbox 3.7.0, AMDGPU.jl 2.13.0 (HIP 7.17.26434 from the downloaded artifacts, ROCm_Runtime 10.2.0), KernelAbstractions 0.10.9
Analysis
What the two threads do (Julia's Profile on the AMDGPU case, one CPU, C = true, trimmed):
Thread 1 (caller), 552 samples
272 submit! -> notify(worker.work) -> unlock -> notifywaiters -> schedule -> wake_thread -> __pthread_mutex_unlock
280 wait(request.done) -> wait(::GenericCondition{ReentrantLock}) -> relockall -> slowlock
190 of them in lock(::Threads.SpinLock) itself
Thread 2 (wait worker), 552 samples
73 hipStreamSynchronize -> rocr::core::InterruptSignal::WaitRelaxed
192 notify(request.done) -> unlock -> notifywaiters -> schedule -> wake_thread -> __pthread_mutex_unlock
287 wait(worker.work) -> wait(::GenericCondition{ReentrantLock}) -> relockall -> slowlock
174 of them in lock(::Threads.SpinLock) itself
On Julia 1.13, Base.Event wraps a Threads.Condition. In notify(::Event), unlock finds a parked waiter and calls notifywaiters. That holds the cond_wait spin lock of the ReentrantLock while it schedules the waiting task, which wakes that task's thread. On a single CPU, the woken thread preempts the notifier right away, while the notifier still holds the spin lock. The woken task then retakes the ReentrantLock (relockall -> slowlock -> lock(c.lock)). lock(::SpinLock) never gives up the CPU, so it spins until the slice expires and the notifier runs again. The profile shows both sides of this, twice per wait: one thread is stopped in wake_thread inside notifywaiters, and the other spins in lock(::SpinLock).
Measurements that support this (AMDGPU case, one CPU, 400 waits each, medians unless stated otherwise):
| Change | Median wait |
|---|---|
| none | 6.98 ms |
blocking = true |
0.19 ms |
| two CPUs | 0.19 ms |
| two Julia threads on one CPU | 6.98 ms |
spin = false |
7.00 ms |
JULIA_THREAD_SLEEP_THRESHOLD=0 / infinite |
5.99 ms / 6.97 ms |
hipSetDeviceFlags Spin, Yield or BlockingSync (confirmed with hipGetDeviceFlags) |
6.98 ms each |
EEVDF slice set to 0.2 ms for every thread (sched_setattr, sched_runtime) |
1.98 ms |
| EEVDF slice set to 10 ms for every thread | 20.98 ms |
SCHED_BATCH (chrt -b 0, no wake-up preemption) |
0.32 ms |
SCHED_BATCH and JULIA_THREAD_SLEEP_THRESHOLD=0 |
0.19 ms |
in-process patch making lock(::Threads.SpinLock) call sched_yield after 100 spins (the YieldingSpinLock algorithm) |
0.34 ms |
- The extra time follows the scheduler slice: about two slices, rounded up to whole milliseconds (the measured waits cluster at whole milliseconds, which fits slice enforcement at the 1 ms tick).
- Removing wake-up preemption (
SCHED_BATCH), or letting the spinning waiter give up the CPU, removes almost all of it. - HIP's wait policy and Julia's scheduler spinning are not the cause. Neither do two Julia threads help, as long as they share one CPU.
- While waiting, the caller and the worker each used about 3.4 ms of CPU time per wait and had about 5 involuntary context switches per wait (from
/proc/self/task/*/sched). With two CPUs, no thread used more than 0.21 ms per wait. - Varying the kernel length: 50 µs takes 6.98 ms, 0.9 ms takes 6.99 ms, and 4.5 ms takes 8.98 ms. Kernels short enough for the polling budget (about 25 µs here) are unaffected.
Without a GPU, a plain Base.Event ping-pong between two Julia threads on one CPU shows the same pattern in its tail. The median round trip is 103 µs, but the p90 is 7990 µs (0.7 µs and 0.9 µs on two CPUs). This points at Base: Threads.Condition and ReentrantLock hold a non-yielding spin lock while they wake a thread. cooperative_wait turns it into a fixed cost on every slow-path wait.
I have only tested AMDGPU.jl on Linux. CUDA.jl (CUDACore/lib/cudadrv/synchronization.jl) and Metal.jl call cooperative_wait without subscribe, so they go through the same worker handoff. I expect the same behavior there, but I have not measured it. The KernelAbstractions PoCL back end uses subscribe, which #27 already fixed. I also expect a fully loaded multi-core machine to hit this whenever the woken thread lands on the notifier's CPU, as in the #27 report, but I have not measured that either.
Suggested fix
- Hand requests to workers and signal their completion through the same kind of condition that completions use (
GenericCondition{YieldingSpinLock}plus an atomic state), instead ofBase.Event. Then a woken thread that finds the lock held gives up the CPU after brief spinning, and the preempted notifier can release it. The in-process patch above (which changed everyThreads.SpinLock, so it is broader than this fix) brought the one-CPU wait from 6.98 ms to 0.34 ms. A targeted change would need its own measurement, and the interrupt and cancellation handling aroundrequest.donewould have to be kept. - Alternatively, wake the waiter only after the lock is released. Don't let tasks woken by completion callbacks spin on a preempted lock holder #27 notes that this needs
GenericConditioninternals that differ between Julia versions. - A cheaper but partial option is to wait on the calling thread when the process can use only one CPU (
sched_getaffinityoruv_thread_getaffinity). This has drawbacks. It blocks the thread, so other tasks cannot run during the wait. For AMDGPU, that includes the tasks that serve device hostcalls, so a kernel that uses them could deadlock with one Julia thread. It also misses CPU quotas that do not show up in the affinity mask, and loaded multi-core machines. And the affinity can change at run time.
A fix in Base (a spin lock in Threads.Condition / ReentrantLock that yields, or waking after unlocking) would help every user of Base.Event. That probably deserves its own Julia issue. Fixing GPUToolbox does not have to wait for it.
Workarounds until then: AMDGPU.synchronize(; blocking = true), the nonblocking_synchronization = false preference, or giving the process at least two CPUs.
Co-written with Claude Opus 5.5.
Activity
PraneethMerugu commentedon Nov 27, 2026
I filed the Base-level cause, with a reproducer that uses only Base, as JuliaLang/julia#65310.
Co-written with Claude Opus 5.5.