Skip to content

Commit bddfc46

Browse files
Wait for all threads that aren't killed daemon threads to finalize.
1 parent 51d960e commit bddfc46

File tree

1 file changed

+22
-5
lines changed

1 file changed

+22
-5
lines changed

Modules/_threadmodule.c

Lines changed: 22 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ static struct PyModuleDef thread_module;
2727
struct module_thread {
2828
PyThreadState *tstate;
2929
int daemonic;
30+
int running;
3031
PyThread_type_lock lifetime_mutex;
3132
int lifetime_mutex_held;
3233
struct module_thread *prev;
@@ -83,13 +84,24 @@ static void
8384
module_threads_fini(struct module_threads *threads)
8485
{
8586
// Wait for all the threads to finalize.
86-
PyThread_acquire_lock(threads->mutex, WAIT_LOCK);
87-
while (threads->head != NULL) {
88-
PyThread_release_lock(threads->mutex);
89-
// XXX Sleep?
87+
int done = 0;
88+
while (!done) {
89+
done = 1;
9090
PyThread_acquire_lock(threads->mutex, WAIT_LOCK);
91+
struct module_thread *mt = threads->head;
92+
while (mt != NULL) {
93+
if (mt->running) {
94+
assert(mt->daemonic);
95+
// It was killed with PyThread_exit_thread().
96+
}
97+
else {
98+
done = 0;
99+
break;
100+
}
101+
mt = mt->next;
102+
}
103+
PyThread_release_lock(threads->mutex);
91104
}
92-
PyThread_release_lock(threads->mutex);
93105

94106
PyThread_free_lock(threads->mutex);
95107
}
@@ -147,6 +159,7 @@ add_module_thread(struct module_threads *threads,
147159
}
148160
mt->tstate = tstate;
149161
mt->daemonic = daemonic;
162+
mt->running = 0;
150163
mt->prev = NULL;
151164
mt->next = NULL;
152165

@@ -192,13 +205,17 @@ module_thread_starting(struct module_thread *mt)
192205
// when add_module_thread() was called.
193206
PyThread_acquire_lock(mt->lifetime_mutex, WAIT_LOCK);
194207
mt->lifetime_mutex_held = 1;
208+
209+
mt->running = 1;
195210
}
196211

197212
static void
198213
module_thread_finished(struct module_thread *mt)
199214
{
200215
mt->tstate->interp->threads.count--;
201216

217+
mt->running = 0;
218+
202219
// Notify other threads that this one is done.
203220
// XXX Do it explicitly here rather than via tstate.on_delete().
204221
}

0 commit comments

Comments
 (0)