Skip to content

Commit e4fb11c

Browse files
committed
Merge branch 'pythongh-114271-remove-tstate_lock' into nogil-integration
2 parents f2b7a25 + 3121623 commit e4fb11c

File tree

12 files changed

+767
-639
lines changed

12 files changed

+767
-639
lines changed

Include/cpython/pystate.h

-26
Original file line numberDiff line numberDiff line change
@@ -161,32 +161,6 @@ struct _ts {
161161
*/
162162
uintptr_t critical_section;
163163

164-
/* Called when a thread state is deleted normally, but not when it
165-
* is destroyed after fork().
166-
* Pain: to prevent rare but fatal shutdown errors (issue 18808),
167-
* Thread.join() must wait for the join'ed thread's tstate to be unlinked
168-
* from the tstate chain. That happens at the end of a thread's life,
169-
* in pystate.c.
170-
* The obvious way doesn't quite work: create a lock which the tstate
171-
* unlinking code releases, and have Thread.join() wait to acquire that
172-
* lock. The problem is that we _are_ at the end of the thread's life:
173-
* if the thread holds the last reference to the lock, decref'ing the
174-
* lock will delete the lock, and that may trigger arbitrary Python code
175-
* if there's a weakref, with a callback, to the lock. But by this time
176-
* _PyRuntime.gilstate.tstate_current is already NULL, so only the simplest
177-
* of C code can be allowed to run (in particular it must not be possible to
178-
* release the GIL).
179-
* So instead of holding the lock directly, the tstate holds a weakref to
180-
* the lock: that's the value of on_delete_data below. Decref'ing a
181-
* weakref is harmless.
182-
* on_delete points to _threadmodule.c's static release_sentinel() function.
183-
* After the tstate is unlinked, release_sentinel is called with the
184-
* weakref-to-lock (on_delete_data) argument, and release_sentinel releases
185-
* the indirectly held lock.
186-
*/
187-
void (*on_delete)(void *);
188-
void *on_delete_data;
189-
190164
int coroutine_origin_tracking_depth;
191165

192166
PyObject *async_gen_firstiter;

Include/internal/pycore_lock.h

-10
Original file line numberDiff line numberDiff line change
@@ -153,16 +153,6 @@ PyAPI_FUNC(void) PyEvent_Wait(PyEvent *evt);
153153
// and 0 if the timeout expired or thread was interrupted.
154154
PyAPI_FUNC(int) PyEvent_WaitTimed(PyEvent *evt, PyTime_t timeout_ns);
155155

156-
// A one-time event notification with reference counting.
157-
typedef struct _PyEventRc {
158-
PyEvent event;
159-
Py_ssize_t refcount;
160-
} _PyEventRc;
161-
162-
_PyEventRc *_PyEventRc_New(void);
163-
void _PyEventRc_Incref(_PyEventRc *erc);
164-
void _PyEventRc_Decref(_PyEventRc *erc);
165-
166156
// _PyRawMutex implements a word-sized mutex that that does not depend on the
167157
// parking lot API, and therefore can be used in the parking lot
168158
// implementation.

Include/internal/pycore_pythread.h

+1-1
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ struct _pythread_runtime_state {
7878
} stubs;
7979
#endif
8080

81-
// Linked list of ThreadHandleObjects
81+
// Linked list of ThreadHandles
8282
struct llist_node handles;
8383
};
8484

Lib/test/test_audit.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -209,7 +209,7 @@ def test_threading(self):
209209
expected = [
210210
("_thread.start_new_thread", "(<test_func>, (), None)"),
211211
("test.test_func", "()"),
212-
("_thread.start_joinable_thread", "(<test_func>,)"),
212+
("_thread.start_joinable_thread", "(<test_func>, 1, None)"),
213213
("test.test_func", "()"),
214214
]
215215

Lib/test/test_concurrent_futures/test_process_pool.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -201,13 +201,13 @@ def test_python_finalization_error(self):
201201
# QueueFeederThread.
202202
orig_start_new_thread = threading._start_joinable_thread
203203
nthread = 0
204-
def mock_start_new_thread(func, *args):
204+
def mock_start_new_thread(func, *args, **kwargs):
205205
nonlocal nthread
206206
if nthread >= 1:
207207
raise RuntimeError("can't create new thread at "
208208
"interpreter shutdown")
209209
nthread += 1
210-
return orig_start_new_thread(func, *args)
210+
return orig_start_new_thread(func, *args, **kwargs)
211211

212212
with support.swap_attr(threading, '_start_joinable_thread',
213213
mock_start_new_thread):

Lib/test/test_thread.py

+48
Original file line numberDiff line numberDiff line change
@@ -289,6 +289,54 @@ def joiner():
289289
with self.assertRaisesRegex(RuntimeError, "Cannot join current thread"):
290290
raise error
291291

292+
def test_join_with_timeout(self):
293+
lock = thread.allocate_lock()
294+
lock.acquire()
295+
296+
def thr():
297+
lock.acquire()
298+
299+
with threading_helper.wait_threads_exit():
300+
handle = thread.start_joinable_thread(thr)
301+
handle.join(0.1)
302+
self.assertFalse(handle.is_done())
303+
lock.release()
304+
handle.join()
305+
self.assertTrue(handle.is_done())
306+
307+
def test_join_unstarted(self):
308+
handle = thread._ThreadHandle()
309+
with self.assertRaisesRegex(RuntimeError, "thread not started"):
310+
handle.join()
311+
312+
def test_set_done_unstarted(self):
313+
handle = thread._ThreadHandle()
314+
with self.assertRaisesRegex(RuntimeError, "thread not started"):
315+
handle._set_done()
316+
317+
def test_start_duplicate_handle(self):
318+
lock = thread.allocate_lock()
319+
lock.acquire()
320+
321+
def func():
322+
lock.acquire()
323+
324+
handle = thread._ThreadHandle()
325+
with threading_helper.wait_threads_exit():
326+
thread.start_joinable_thread(func, handle=handle)
327+
with self.assertRaisesRegex(RuntimeError, "thread already started"):
328+
thread.start_joinable_thread(func, handle=handle)
329+
lock.release()
330+
handle.join()
331+
332+
def test_start_with_none_handle(self):
333+
def func():
334+
pass
335+
336+
with threading_helper.wait_threads_exit():
337+
handle = thread.start_joinable_thread(func, handle=None)
338+
handle.join()
339+
292340

293341
class Barrier:
294342
def __init__(self, num_threads):

Lib/test/test_threading.py

+1-60
Original file line numberDiff line numberDiff line change
@@ -406,7 +406,7 @@ def run(self):
406406

407407
def test_limbo_cleanup(self):
408408
# Issue 7481: Failure to start thread should cleanup the limbo map.
409-
def fail_new_thread(*args):
409+
def fail_new_thread(*args, **kwargs):
410410
raise threading.ThreadError()
411411
_start_joinable_thread = threading._start_joinable_thread
412412
threading._start_joinable_thread = fail_new_thread
@@ -901,41 +901,6 @@ def f():
901901
rc, out, err = assert_python_ok("-c", code)
902902
self.assertEqual(err, b"")
903903

904-
def test_tstate_lock(self):
905-
# Test an implementation detail of Thread objects.
906-
started = _thread.allocate_lock()
907-
finish = _thread.allocate_lock()
908-
started.acquire()
909-
finish.acquire()
910-
def f():
911-
started.release()
912-
finish.acquire()
913-
time.sleep(0.01)
914-
# The tstate lock is None until the thread is started
915-
t = threading.Thread(target=f)
916-
self.assertIs(t._tstate_lock, None)
917-
t.start()
918-
started.acquire()
919-
self.assertTrue(t.is_alive())
920-
# The tstate lock can't be acquired when the thread is running
921-
# (or suspended).
922-
tstate_lock = t._tstate_lock
923-
self.assertFalse(tstate_lock.acquire(timeout=0), False)
924-
finish.release()
925-
# When the thread ends, the state_lock can be successfully
926-
# acquired.
927-
self.assertTrue(tstate_lock.acquire(timeout=support.SHORT_TIMEOUT), False)
928-
# But is_alive() is still True: we hold _tstate_lock now, which
929-
# prevents is_alive() from knowing the thread's end-of-life C code
930-
# is done.
931-
self.assertTrue(t.is_alive())
932-
# Let is_alive() find out the C code is done.
933-
tstate_lock.release()
934-
self.assertFalse(t.is_alive())
935-
# And verify the thread disposed of _tstate_lock.
936-
self.assertIsNone(t._tstate_lock)
937-
t.join()
938-
939904
def test_repr_stopped(self):
940905
# Verify that "stopped" shows up in repr(Thread) appropriately.
941906
started = _thread.allocate_lock()
@@ -1101,30 +1066,6 @@ def checker():
11011066
self.assertEqual(threading.getprofile(), old_profile)
11021067
self.assertEqual(sys.getprofile(), old_profile)
11031068

1104-
@cpython_only
1105-
def test_shutdown_locks(self):
1106-
for daemon in (False, True):
1107-
with self.subTest(daemon=daemon):
1108-
event = threading.Event()
1109-
thread = threading.Thread(target=event.wait, daemon=daemon)
1110-
1111-
# Thread.start() must add lock to _shutdown_locks,
1112-
# but only for non-daemon thread
1113-
thread.start()
1114-
tstate_lock = thread._tstate_lock
1115-
if not daemon:
1116-
self.assertIn(tstate_lock, threading._shutdown_locks)
1117-
else:
1118-
self.assertNotIn(tstate_lock, threading._shutdown_locks)
1119-
1120-
# unblock the thread and join it
1121-
event.set()
1122-
thread.join()
1123-
1124-
# Thread._stop() must remove tstate_lock from _shutdown_locks.
1125-
# Daemon threads must never add it to _shutdown_locks.
1126-
self.assertNotIn(tstate_lock, threading._shutdown_locks)
1127-
11281069
def test_locals_at_exit(self):
11291070
# bpo-19466: thread locals must not be deleted before destructors
11301071
# are called

0 commit comments

Comments
 (0)