Skip to content

Commit f53de6d

Browse files
author
Joel Collins
committed
Fixed cleanup and context bugs
1 parent 323a709 commit f53de6d

File tree

1 file changed

+14
-10
lines changed

1 file changed

+14
-10
lines changed

labthings/core/tasks/pool.py

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,10 @@
1-
import threading
21
import logging
32
from functools import wraps
43
from gevent import getcurrent
54

65
from .thread import TaskThread
76

8-
from flask import copy_current_request_context
7+
from flask import copy_current_request_context, has_request_context
98

109

1110
class TaskMaster:
@@ -38,21 +37,26 @@ def states(self):
3837

3938
def new(self, f, *args, **kwargs):
4039
# copy_current_request_context allows threads to access flask current_app
41-
task = TaskThread(
42-
target=copy_current_request_context(f), args=args, kwargs=kwargs
43-
)
40+
if has_request_context():
41+
target = copy_current_request_context(f)
42+
else:
43+
target = f
44+
task = TaskThread(target=target, args=args, kwargs=kwargs)
4445
self._tasks.append(task)
4546
return task
4647

4748
def remove(self, task_id):
4849
for task in self._tasks:
49-
if (task.id == task_id) and not task.isAlive():
50-
del task
50+
if (str(task.id) == str(task_id)) and task.dead:
51+
self._tasks.remove(task)
5152

5253
def cleanup(self):
53-
for task in self._tasks:
54-
if not task.isAlive():
55-
del task
54+
for i, task in enumerate(self._tasks):
55+
if task.dead:
56+
# Mark for delection
57+
self._tasks[i] = None
58+
# Remove items marked for deletion
59+
self._tasks = [t for t in self._tasks if t]
5660

5761

5862
# Task management

0 commit comments

Comments
 (0)