Skip to content

Commit 5692bb7

Browse files
authored
Manage CPython thread states automatically across Julia tasks (#824)
* Manage Python thread states per Julia task * Restore Julia 1.10 thread state compatibility * Keep Python error handling within regions * Address thread-state review feedback * Document automatic thread-state migration * Remove jl_call_nogil and benchmark regions * Fast-path already attached Python regions * Avoid GIL callback lock inversion * Add concurrent Python region tests * Fix benchmark Python dependencies * Fix Python 3.10 callback GIL detection * Document Julia 1.11 foreign-thread compilation caveat * remove duplicate dep * Fix benchmark compatibility with revisions without pyregion --------- Co-authored-by: Christopher Rowley <github.com/cjdoris>
1 parent 8cf2bfb commit 5692bb7

41 files changed

Lines changed: 1052 additions & 490 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎AGENTS.md‎

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,28 @@
11
# Repository Instructions
22

33
## Running tests
4-
- **Julia tests**: Run from the project root with `julia --project -e 'using Pkg; Pkg.test()'`. Expect a warning about the General registry being unreachable in locked-down environments; the suite still finishes (PyCall tests are marked broken/Skipped).
4+
- **Julia tests**: Run from the project root with `julia --project -e 'using Pkg; Pkg.test()'`. Expect a warning about the General registry being unreachable in locked-down environments; PyCall tests are marked broken/skipped. With the currently installed Julia 1.13.1, the functional tests pass but Aqua's persistent-task subprocess check may fail because its `done.log` is not created.
55
- **Python tests**:
66
- Copy `pysrc/juliacall/juliapkg-dev.json` to `pysrc/juliacall/juliapkg.json` before running (do **not** commit this copy).
77
- Execute with `uv run pytest -s --nbval ./pytest` (add `--cov=pysrc` when coverage is needed).
8-
- Sometimes `juliapkg` requires Julia 1.10–1.11; `juliaup` already provides 1.11.7 in this environment.
8+
- Sometimes `juliapkg` requires Julia 1.10–1.11. Juliaup provides Julia 1.11.9
9+
through the `1.11` channel. JuliaPkg selecting Julia 1.13.1 under
10+
uv's downloaded Python 3.10 fails to load `libjulia-codegen` because the Python
11+
process has loaded a `libstdc++.so.6` that lacks `GLIBCXX_3.4.30`. Set
12+
`PYTHON_JULIAPKG_EXE` to the absolute path of the Julia 1.11 executable when
13+
running this combination; `JULIAUP_CHANNEL=1.11` does not affect JuliaPkg's
14+
executable discovery here. To test Julia 1.12 or 1.13 instead, also prepend the
15+
repository's `.CondaPkg/.pixi/envs/default/lib` directory to `LD_LIBRARY_PATH` so
16+
the process uses its newer `libstdc++`.
17+
- `julia --project=docs docs/make.jl` requires a valid Git `origin` so Documenter can infer
18+
source links; it fails during `makedocs` in checkouts without one.
919

1020
The majority of tests live in the Julia package; Python tests cover functionality that cannot be exercised from Julia (e.g., JuliaCall-specific behavior). Run both suites—typically Julia first—in whichever order makes sense.
1121

1222
## Branch and CI compatibility
1323
- On `v1`, JuliaCall uses `jl_eval` (returning a Julia wrapper), whereas `main` uses `seval`. Adapt tests brought over from `main` accordingly.
1424
- The benchmark suite is shared across the compared revisions: `main` uses `pydel!`, while `v1` uses `unsafe_pydel`.
25+
- `main` does not have `@pyregion`. Benchmark region wrappers must select a plain-body fallback before macro expansion; a runtime conditional around an unavailable macro still fails when loading the suite.
1526
- Julia CI caches can preserve Conda's build metadata without its root environment. Rebuild `Conda` before building `PyCall` or running tests to recreate that directory.
1627
- In restricted sandboxes, both suites need approval to write to the shared caches (`~/.julia` and `~/.cache/uv`).
1728
- `pysrc/juliacall/juliapkg.json` is tracked; restore its original contents after using the development copy for Python tests.

‎CHANGELOG.md‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,19 @@
1212
* Python errors no longer automatically set `sys.last_traceback` etc. when displayed from Julia.
1313
* Added [`fix_qt_plugin_path` preference](@ref pythoncall-config), replacing `CONFIG.auto_fix_qt_plugin_path`.
1414
* Removed `PythonCall.CONFIG`.
15+
* Changes to multi-threading:
16+
* PythonCall APIs now manage CPython thread states automatically and can be called from
17+
any Julia task or thread without manually locking the GIL.
18+
* Added the optional, nestable `@pyregion` and `@pyregionbreak` macros. These are
19+
performance and concurrency hints rather than correctness requirements.
20+
* Removed the `PythonCall.GIL` module. Ordinary PythonCall operations replace
21+
`GIL.lock`, and `@pyregionbreak` replaces `GIL.unlock` when an enclosing region needs
22+
to relinquish Python resources around yielding or blocking Julia code.
23+
* JuliaCall now relinquishes and restores Python resources automatically while running
24+
Julia code, including Python-to-Julia callbacks.
25+
* Removed JuliaCall's `jl_call_nogil` method; ordinary calls now provide its behavior.
26+
* Python-object finalizers no longer attach a Python thread state. Pending decrefs are
27+
queued until a state is already attached or `PythonCall.GC.gc()` drains the queue.
1528
* Changes to `PythonCall.GC` (now more like `Base.GC`):
1629
* `enable(true)` replaces `enable()`.
1730
* `enable(false)` replaces `disable()`.

‎benchmark/Project.toml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
11
[deps]
22
BenchmarkTools = "6e4b80f9-dd63-53aa-95a3-0cdb28fa8baf"
3+
CondaPkg = "992eb4ea-22a4-4c89-a5bb-47a3300528ab"
34
PythonCall = "6099a3de-0909-46bc-b1f4-468b9a2dfc0d"

‎benchmark/benchmarks.jl‎

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,15 @@ using PythonCall: pyimport, pydict, pystr, pyrange
55
# The same suite runs against main and v1, which use different names.
66
const benchmark_pydel = isdefined(PythonCall, :pydel!) ? PythonCall.pydel! : PythonCall.unsafe_pydel
77

8+
# main has no regions: run the same body without the outer region there.
9+
# Select before macro expansion so an unavailable @pyregion is never expanded.
10+
macro benchmark_pyregion(ex)
11+
if isdefined(PythonCall, Symbol("@pyregion"))
12+
return esc(:(PythonCall.@pyregion $ex))
13+
end
14+
return esc(ex)
15+
end
16+
817
const SUITE = BenchmarkGroup()
918

1019
function test_pydict_init()
@@ -53,6 +62,49 @@ end
5362
SUITE["basic"]["@py"]["pydict"]["init"] = @benchmarkable test_atpy(Val(false))
5463
SUITE["basic"]["@py"]["pydict"]["pydel"] = @benchmarkable test_atpy(Val(true))
5564

65+
function test_region_pythoncall(x, n)
66+
ans = 0
67+
for _ = 1:n
68+
ans += pylen(x)
69+
end
70+
return ans
71+
end
72+
73+
function test_region_pythoncall_outer(x, n)
74+
@benchmark_pyregion begin
75+
ans = 0
76+
for _ = 1:n
77+
ans += pylen(x)
78+
end
79+
return ans
80+
end
81+
end
82+
83+
function test_region_capi(x, n)
84+
@benchmark_pyregion begin
85+
ans = 0
86+
for _ = 1:n
87+
ans += PythonCall.C.PyObject_Length(x)
88+
end
89+
return ans
90+
end
91+
end
92+
93+
const REGION_BENCHMARK_LENGTH = 1000
94+
95+
SUITE["region"]["pythoncall"] = @benchmarkable(
96+
test_region_pythoncall(x, REGION_BENCHMARK_LENGTH),
97+
setup=(x = pytuple((1, 2, 3))),
98+
)
99+
SUITE["region"]["pythoncall_outer"] = @benchmarkable(
100+
test_region_pythoncall_outer(x, REGION_BENCHMARK_LENGTH),
101+
setup=(x = pytuple((1, 2, 3))),
102+
)
103+
SUITE["region"]["capi_outer"] = @benchmarkable(
104+
test_region_capi(x, REGION_BENCHMARK_LENGTH),
105+
setup=(x = pytuple((1, 2, 3))),
106+
)
107+
56108

57109
include("gcbench.jl")
58110
using .GCBench: append_lots

‎docs/src/faq.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,9 @@ Alternatively, to force PyCall to use the same interpreter as PythonCall, set th
1212

1313
## [Is PythonCall/JuliaCall thread safe?](@id faq-multi-threading)
1414

15-
Yes, as of v0.9.22, provided you handle the GIL correctly. See the guides for
15+
Yes. PythonCall and JuliaCall manage the required Python thread states automatically, so
16+
PythonCall operations can be used from any Julia task or thread without explicit GIL
17+
handling. See the guides for
1618
[PythonCall](@ref jl-multi-threading) and [JuliaCall](@ref py-multi-threading).
1719

1820
Before, tricks such as disabling the garbage collector were required. See the

‎docs/src/juliacall-reference.md‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,6 @@ and ending with `__` (since these are Python special methods) or starting with `
7070
- `jl_callback(*args, **kwargs)`: Calls the Julia object with the given arguments.
7171
Unlike ordinary calling syntax, the arguments are passed as `Py` objects instead of
7272
being converted.
73-
- `jl_call_nogil(*args, **kwargs)`: Call this with the GIL disabled.
7473
- `jl_display()`: Display the object using Julia's display mechanism.
7574
- `jl_eval(expr)`: If the object is a Julia `Module`, evaluates the given expression.
7675
- `jl_help()`: Display help for the object.

‎docs/src/juliacall.md‎

Lines changed: 20 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -155,59 +155,50 @@ be configured in two ways:
155155
From v0.9.22, JuliaCall supports multi-threading in Julia and/or Python, with some
156156
caveats.
157157

158-
Most importantly, you can only call Python code while Python's
159-
[Global Interpreter Lock (GIL)](https://docs.python.org/3/glossary.html#term-global-interpreter-lock)
160-
is locked by the current thread. You can use JuliaCall from any Python thread, and the GIL
161-
will be locked whenever any JuliaCall function is used. However, to leverage the benefits
162-
of multi-threading, you can unlock the GIL while executing any Julia code that does not
163-
interact with Python.
164-
165-
The simplest way to do this is using the `_jl_call_nogil` method on Julia functions to
166-
call the function with the GIL unlocked.
158+
JuliaCall borrows the Python thread state which entered Julia and automatically detaches it
159+
while arbitrary Julia code runs. Nested Python interaction from that Julia code temporarily
160+
reattaches the same state, and the borrowed state is restored before returning to Python.
167161

168162
```python
169163
from concurrent.futures import ThreadPoolExecutor, wait
170164
from juliacall import Main as jl
171165
pool = ThreadPoolExecutor(4)
172-
fs = [pool.submit(jl.Libc.systemsleep._jl_call_nogil, 5) for _ in range(4)]
166+
fs = [pool.submit(jl.Libc.systemsleep, 5) for _ in range(4)]
173167
wait(fs)
174168
```
175169

176-
In the above example, we call `Libc.systemsleep(5)` on four threads. Because we
177-
called it with `_jl_call_nogil`, the GIL was unlocked, allowing the threads to run in
178-
parallel, taking about 5 seconds in total.
170+
PythonCall operations nested inside Julia callbacks are safe without explicit region calls.
179171

180-
If we did not use `_jl_call_nogil` (i.e. if we did `pool.submit(jl.Libc.systemsleep, 5)`)
181-
then the above code will take 20 seconds because the sleeps run one after another.
172+
You can also use [multi-threading from Julia](@ref jl-multi-threading).
182173

183-
It is very important that any function called with `_jl_call_nogil` does not interact
184-
with Python at all unless it re-locks the GIL first, such as by using
185-
[`PythonCall.GIL.@lock`](@ref).
174+
### Caveat: First-time compilation on Julia 1.11
186175

187-
You can also use [multi-threading from Julia](@ref jl-multi-threading).
176+
On Julia 1.11, simultaneously entering a Julia call path which has not yet been compiled
177+
from multiple Python-created threads can deadlock in Julia's compiler and garbage collector.
178+
When supporting Julia 1.11, call the function once with representative argument types on a
179+
single thread before submitting it to a Python thread pool. This limitation does not apply to
180+
Julia 1.12 or later.
181+
182+
Python-created threads are adopted by Julia automatically when they enter JuliaCall. Do not
183+
call `jl_adopt_thread()` yourself.
188184

189185
### Caveat: Julia's task scheduler
190186

191-
If you try the above example with a Julia function that yields to the task scheduler,
192-
such as `sleep` instead of `Libc.systemsleep`, then you will likely experience a hang.
187+
If you use a Julia function which yields to the task scheduler, such as `sleep` instead of
188+
`Libc.systemsleep` in the example above, the Python thread waiting for the futures must
189+
periodically yield to Julia so that the Julia tasks can finish:
193190

194-
In this case, you need to yield back to Julia's scheduler periodically to allow the task
195-
to continue. You can use the following pattern instead of `wait(fs)`:
196191
```python
197192
jl_yield = getattr(jl, "yield")
198193
while True:
199-
# yield to Julia's task scheduler
200194
jl_yield()
201-
# wait for up to 0.1 seconds for the threads to finish
202195
state = wait(fs, timeout=0.1)
203-
# if they finished then stop otherwise try again
204196
if not state.not_done:
205197
break
206198
```
207199

208-
Set the `timeout` parameter smaller to let Julia's scheduler cycle more frequently.
209-
210-
Future versions of JuliaCall may provide tooling to make this simpler.
200+
This scheduler requirement is independent of Python thread-state management; ordinary
201+
JuliaCall calls still relinquish and restore Python resources automatically.
211202

212203
### [Caveat: Signal handling](@id py-multi-threading-signal-handling)
213204

‎docs/src/pythoncall-reference.md‎

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -222,14 +222,15 @@ Py(x::MyType) = x.py
222222

223223
## Multi-threading
224224

225-
These functions are not exported. They support multi-threading of Python and/or Julia.
226-
See also [`juliacall.AnyValue._jl_call_nogil`](@ref julia-wrappers).
225+
PythonCall manages Python thread state automatically. These exported macros are optional
226+
performance and concurrency hints; users normally do not need them for correctness.
227+
228+
```@docs
229+
@pyregion
230+
@pyregionbreak
231+
```
227232

228233
```@docs
229-
PythonCall.GIL.lock
230-
PythonCall.GIL.@lock
231-
PythonCall.GIL.unlock
232-
PythonCall.GIL.@unlock
233234
PythonCall.GC.gc
234235
```
235236

‎docs/src/pythoncall.md‎

Lines changed: 15 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -471,42 +471,36 @@ See [Installing Python packages](@ref python-deps).
471471

472472
Multi-threading support is experimental and can change without notice.
473473

474-
From v0.9.22, PythonCall supports multi-threading in Julia and/or Python, with some
475-
caveats.
476-
477-
Most importantly, you can only call Python code while Python's
478-
[Global Interpreter Lock (GIL)](https://docs.python.org/3/glossary.html#term-global-interpreter-lock)
479-
is locked by the current thread. Ordinarily, the GIL is locked by the main thread in Julia,
480-
so if you want to run Python code on any other thread, you must unlock the GIL from the
481-
main thread and then re-lock it while running any Python code on other threads.
482-
483-
This is made possible by the macros [`PythonCall.GIL.@unlock`](@ref) and
484-
[`PythonCall.GIL.@lock`](@ref) or the functions [`PythonCall.GIL.unlock`](@ref) and
485-
[`PythonCall.GIL.lock`](@ref) with this pattern:
474+
PythonCall APIs automatically establish the Python thread state they need, so ordinary
475+
operations can be called from any Julia task or thread without explicit locking. The
476+
optional [`@pyregion`](@ref) macro amortizes those transitions across straight-line,
477+
Python-heavy work. Use [`@pyregionbreak`](@ref) around Julia-heavy code which deliberately
478+
yields, waits, or blocks cooperatively:
486479

487480
```julia
488-
PythonCall.GIL.@unlock Threads.@threads for i in 1:4
489-
PythonCall.GIL.@lock pyimport("time").sleep(5)
481+
Threads.@threads for i in 1:4
482+
@pyregion pyimport("time").sleep(5)
490483
end
491484
```
492485

493486
In the above example, we call `time.sleep(5)` four times in parallel. If Julia was
494487
started with at least four threads (`julia -t4`) then the above code will take about
495488
5 seconds.
496489

497-
Both `@unlock` and `@lock` are important. If the GIL were not unlocked, then a deadlock
498-
would occur when attempting to lock the already-locked GIL from the threads. If the GIL
499-
were not re-locked, then Python would crash when interacting with it.
490+
Both region macros nest arbitrarily, and neither is required for correctness. A nested
491+
PythonCall operation inside `@pyregionbreak` temporarily re-enters Python automatically.
492+
On a GIL-enabled Python, attaching a state can block that Julia worker while CPython
493+
arbitrates access; free-threaded Python uses the same state-management machinery.
500494

501495
With multiple Julia threads you need exactly one interactive thread, see the [FAQ](@ref faq-multi-threading).
502496

503497
You can also use [multi-threading from Python](@ref py-multi-threading).
504498

505499
### Caveat: Garbage collection
506500

507-
If Julia's GC collects any Python objects from a thread where the GIL is not currently
508-
locked, then those Python objects will not immediately be deleted. Instead they will be
509-
queued to be deleted in a later GC pass.
501+
If Julia's GC collects Python objects while no Python thread state is already attached,
502+
those objects are queued rather than making a finalizer block while attaching a state.
510503

511504
If you find you have many Python objects not being deleted, you can call
512-
[`PythonCall.GC.gc()`](@ref) or `GC.gc()` while the GIL is locked to clear the queue.
505+
[`PythonCall.GC.gc()`](@ref) to clear the queue. An ordinary `GC.gc()` may also clear it
506+
when a Python thread state is already attached, such as inside `@pyregion`.

‎docs/src/v1-migration-guide.md‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,52 @@ The `PythonCall.CONFIG.auto_fix_qt_plugin_path` config has been replaced with th
7777
`pkg> preference add PythonCall fix_qt_plugin_path=false` or the env var
7878
`JULIA_PYTHONCALL_FIX_QT_PLUGIN_PATH=0`.
7979

80+
## Multi-threading
81+
82+
PythonCall now manages CPython thread states automatically. PythonCall operations can be
83+
used from any Julia task or thread, including Julia code entered through JuliaCall, without
84+
manually locking or unlocking the GIL.
85+
86+
The `PythonCall.GIL` module has been removed:
87+
88+
* Remove `PythonCall.GIL.lock` and `PythonCall.GIL.@lock` around individual PythonCall
89+
operations; each operation establishes the Python state it needs automatically.
90+
* For a sequence of straight-line, Python-heavy operations, `@pyregion` is an optional
91+
optimization which amortizes thread-state transitions.
92+
* Instead of `PythonCall.GIL.unlock(f)` or `PythonCall.GIL.@unlock expr` inside such a
93+
region, use `@pyregionbreak f()` or `@pyregionbreak expr`. A region break is useful
94+
around Julia code which may yield, wait, or block cooperatively.
95+
96+
For example, code which previously managed the GIL explicitly:
97+
98+
```julia
99+
PythonCall.GIL.@lock begin
100+
x = pyimport("example").make_value()
101+
PythonCall.GIL.@unlock wait(event)
102+
x.finish()
103+
end
104+
```
105+
106+
can be written as:
107+
108+
```julia
109+
@pyregion begin
110+
x = pyimport("example").make_value()
111+
@pyregionbreak wait(event)
112+
x.finish()
113+
end
114+
```
115+
116+
The outer `@pyregion` can also be omitted; the PythonCall operations remain correct, and
117+
`wait(event)` then needs no annotation. Both macros nest safely.
118+
119+
JuliaCall similarly relinquishes Python resources automatically while arbitrary Julia code
120+
runs. The `_jl_call_nogil` and `jl_call_nogil` methods have been removed; use an ordinary
121+
call instead.
122+
123+
Finalizers no longer attach a Python thread state and block waiting for Python. If prompt
124+
cleanup matters, call `PythonCall.GC.gc()` at a suitable point to drain queued decrefs.
125+
80126
## `PythonCall.GC`
81127

82128
This submodule has been changed to closer mimic the `Base.GC` API.

0 commit comments

Comments
 (0)