Skip to content

Commit 2731913

Browse files
authored
gh-116167: Allow disabling the GIL with PYTHON_GIL=0 or -X gil=0 (#116338)
In free-threaded builds, running with `PYTHON_GIL=0` will now disable the GIL. Follow-up issues track work to re-enable the GIL when loading an incompatible extension, and to disable the GIL by default. In order to support re-enabling the GIL at runtime, all GIL-related data structures are initialized as usual, and disabling the GIL simply sets a flag that causes `take_gil()` and `drop_gil()` to return early.
1 parent 546eb7a commit 2731913

File tree

12 files changed

+163
-1
lines changed

12 files changed

+163
-1
lines changed

Doc/using/cmdline.rst

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -559,6 +559,9 @@ Miscellaneous options
559559
:mod:`__main__`. This can be used to execute code early during Python
560560
initialization. Python needs to be :ref:`built in debug mode <debug-build>`
561561
for this option to exist. See also :envvar:`PYTHON_PRESITE`.
562+
* :samp:`-X gil={0,1}` forces the GIL to be disabled or enabled,
563+
respectively. Only available in builds configured with
564+
:option:`--disable-gil`. See also :envvar:`PYTHON_GIL`.
562565

563566
It also allows passing arbitrary values and retrieving them through the
564567
:data:`sys._xoptions` dictionary.
@@ -601,6 +604,9 @@ Miscellaneous options
601604
.. versionchanged:: 3.13
602605
Added the ``-X cpu_count`` and ``-X presite`` options.
603606

607+
.. versionchanged:: 3.13
608+
Added the ``-X gil`` option.
609+
604610
.. _using-on-controlling-color:
605611

606612
Controlling color
@@ -1138,6 +1144,18 @@ conflict.
11381144

11391145
.. versionadded:: 3.13
11401146

1147+
.. envvar:: PYTHON_GIL
1148+
1149+
If this variable is set to ``1``, the global interpreter lock (GIL) will be
1150+
forced on. Setting it to ``0`` forces the GIL off.
1151+
1152+
See also the :option:`-X gil <-X>` command-line option, which takes
1153+
precedence over this variable.
1154+
1155+
Needs Python configured with the :option:`--disable-gil` build option.
1156+
1157+
.. versionadded:: 3.13
1158+
11411159
Debug-mode variables
11421160
~~~~~~~~~~~~~~~~~~~~
11431161

Include/cpython/initconfig.h

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -181,6 +181,9 @@ typedef struct PyConfig {
181181
int int_max_str_digits;
182182

183183
int cpu_count;
184+
#ifdef Py_GIL_DISABLED
185+
int enable_gil;
186+
#endif
184187

185188
/* --- Path configuration inputs ------------ */
186189
int pathconfig_warnings;

Include/internal/pycore_gil.h

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,11 @@ extern "C" {
2020
#define FORCE_SWITCHING
2121

2222
struct _gil_runtime_state {
23+
#ifdef Py_GIL_DISABLED
24+
/* Whether or not this GIL is being used. Can change from 0 to 1 at runtime
25+
if, for example, a module that requires the GIL is loaded. */
26+
int enabled;
27+
#endif
2328
/* microseconds (the Python API uses seconds, though) */
2429
unsigned long interval;
2530
/* Last PyThreadState holding / having held the GIL. This helps us

Include/internal/pycore_initconfig.h

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -153,6 +153,18 @@ typedef enum {
153153
_PyConfig_INIT_ISOLATED = 3
154154
} _PyConfigInitEnum;
155155

156+
typedef enum {
157+
/* For now, this means the GIL is enabled.
158+
159+
gh-116329: This will eventually change to "the GIL is disabled but can
160+
be reenabled by loading an incompatible extension module." */
161+
_PyConfig_GIL_DEFAULT = -1,
162+
163+
/* The GIL has been forced off or on, and will not be affected by module loading. */
164+
_PyConfig_GIL_DISABLE = 0,
165+
_PyConfig_GIL_ENABLE = 1,
166+
} _PyConfigGILEnum;
167+
156168
// Export for '_testembed' program
157169
PyAPI_FUNC(void) _PyConfig_InitCompatConfig(PyConfig *config);
158170

Lib/subprocess.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -350,7 +350,7 @@ def _args_from_interpreter_flags():
350350
if dev_mode:
351351
args.extend(('-X', 'dev'))
352352
for opt in ('faulthandler', 'tracemalloc', 'importtime',
353-
'frozen_modules', 'showrefcount', 'utf8'):
353+
'frozen_modules', 'showrefcount', 'utf8', 'gil'):
354354
if opt in xoptions:
355355
value = xoptions[opt]
356356
if value is True:

Lib/test/_test_embed_set_config.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
import os
1010
import sys
1111
import unittest
12+
from test import support
1213
from test.support import MS_WINDOWS
1314

1415

@@ -211,6 +212,19 @@ def test_flags(self):
211212
self.set_config(use_hash_seed=1, hash_seed=123)
212213
self.assertEqual(sys.flags.hash_randomization, 1)
213214

215+
if support.Py_GIL_DISABLED:
216+
self.set_config(enable_gil=-1)
217+
self.assertEqual(sys.flags.gil, None)
218+
self.set_config(enable_gil=0)
219+
self.assertEqual(sys.flags.gil, 0)
220+
self.set_config(enable_gil=1)
221+
self.assertEqual(sys.flags.gil, 1)
222+
else:
223+
# Builds without Py_GIL_DISABLED don't have
224+
# PyConfig.enable_gil. sys.flags.gil is always defined to 1, for
225+
# consistency.
226+
self.assertEqual(sys.flags.gil, 1)
227+
214228
def test_options(self):
215229
self.check(warnoptions=[])
216230
self.check(warnoptions=["default", "ignore"])

Lib/test/test_cmd_line.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -869,6 +869,39 @@ def test_pythondevmode_env(self):
869869
self.assertEqual(proc.stdout.rstrip(), 'True')
870870
self.assertEqual(proc.returncode, 0, proc)
871871

872+
@unittest.skipUnless(support.Py_GIL_DISABLED,
873+
"PYTHON_GIL and -X gil only supported in Py_GIL_DISABLED builds")
874+
def test_python_gil(self):
875+
cases = [
876+
# (env, opt, expected, msg)
877+
(None, None, 'None', "no options set"),
878+
('0', None, '0', "PYTHON_GIL=0"),
879+
('1', None, '1', "PYTHON_GIL=1"),
880+
('1', '0', '0', "-X gil=0 overrides PYTHON_GIL=1"),
881+
(None, '0', '0', "-X gil=0"),
882+
(None, '1', '1', "-X gil=1"),
883+
]
884+
885+
code = "import sys; print(sys.flags.gil)"
886+
environ = dict(os.environ)
887+
888+
for env, opt, expected, msg in cases:
889+
with self.subTest(msg, env=env, opt=opt):
890+
environ.pop('PYTHON_GIL', None)
891+
if env is not None:
892+
environ['PYTHON_GIL'] = env
893+
extra_args = []
894+
if opt is not None:
895+
extra_args = ['-X', f'gil={opt}']
896+
897+
proc = subprocess.run([sys.executable, *extra_args, '-c', code],
898+
stdout=subprocess.PIPE,
899+
stderr=subprocess.PIPE,
900+
text=True, env=environ)
901+
self.assertEqual(proc.returncode, 0, proc)
902+
self.assertEqual(proc.stdout.rstrip(), expected)
903+
self.assertEqual(proc.stderr, '')
904+
872905
@unittest.skipUnless(sys.platform == 'win32',
873906
'bpo-32457 only applies on Windows')
874907
def test_argv0_normalization(self):

Lib/test/test_embed.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -523,6 +523,8 @@ class InitConfigTests(EmbeddingTestsMixin, unittest.TestCase):
523523
CONFIG_COMPAT['_pystats'] = 0
524524
if support.Py_DEBUG:
525525
CONFIG_COMPAT['run_presite'] = None
526+
if support.Py_GIL_DISABLED:
527+
CONFIG_COMPAT['enable_gil'] = -1
526528
if MS_WINDOWS:
527529
CONFIG_COMPAT.update({
528530
'legacy_windows_stdio': 0,

Misc/python.man

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -607,6 +607,10 @@ output. Setting it to 0 deactivates this behavior.
607607
.IP PYTHON_HISTORY
608608
This environment variable can be used to set the location of a history file
609609
(on Unix, it is \fI~/.python_history\fP by default).
610+
.IP PYTHON_GIL
611+
If this variable is set to 1, the global interpreter lock (GIL) will be forced
612+
on. Setting it to 0 forces the GIL off. Only available in builds configured
613+
with \fB--disable-gil\fP.
610614
.SS Debug-mode variables
611615
Setting these variables only has an effect in a debug build of Python, that is,
612616
if Python was configured with the

Python/ceval_gil.c

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -219,6 +219,11 @@ drop_gil(PyInterpreterState *interp, PyThreadState *tstate)
219219
// XXX assert(tstate == NULL || !tstate->_status.cleared);
220220

221221
struct _gil_runtime_state *gil = ceval->gil;
222+
#ifdef Py_GIL_DISABLED
223+
if (!gil->enabled) {
224+
return;
225+
}
226+
#endif
222227
if (!_Py_atomic_load_ptr_relaxed(&gil->locked)) {
223228
Py_FatalError("drop_gil: GIL is not locked");
224229
}
@@ -294,6 +299,11 @@ take_gil(PyThreadState *tstate)
294299
assert(_PyThreadState_CheckConsistency(tstate));
295300
PyInterpreterState *interp = tstate->interp;
296301
struct _gil_runtime_state *gil = interp->ceval.gil;
302+
#ifdef Py_GIL_DISABLED
303+
if (!gil->enabled) {
304+
return;
305+
}
306+
#endif
297307

298308
/* Check that _PyEval_InitThreads() was called to create the lock */
299309
assert(gil_created(gil));
@@ -440,6 +450,11 @@ static void
440450
init_own_gil(PyInterpreterState *interp, struct _gil_runtime_state *gil)
441451
{
442452
assert(!gil_created(gil));
453+
#ifdef Py_GIL_DISABLED
454+
// gh-116329: Once it is safe to do so, change this condition to
455+
// (enable_gil == _PyConfig_GIL_ENABLE), so the GIL is disabled by default.
456+
gil->enabled = _PyInterpreterState_GetConfig(interp)->enable_gil != _PyConfig_GIL_DISABLE;
457+
#endif
443458
create_gil(gil);
444459
assert(gil_created(gil));
445460
interp->ceval.gil = gil;

0 commit comments

Comments
 (0)