Skip to content

Commit 54e0b8f

Browse files
committed
Let the worker run tasks on the main thread
When the `queue` parameter is passed with value `"main"`, the task is added to the main thread queue rather than being launched in a new dedicated thread.
1 parent 8c6788e commit 54e0b8f

File tree

1 file changed

+19
-4
lines changed

1 file changed

+19
-4
lines changed

src/appose/python_worker.py

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -183,6 +183,7 @@ class Worker:
183183

184184
def __init__(self):
185185
self.tasks = {}
186+
self.queue: list[Task] = []
186187
self.running = True
187188

188189
# Flag this process as a worker, not a service.
@@ -192,9 +193,16 @@ def __init__(self):
192193
Thread(target=self._cleanup_threads, name="Appose-Janitor").start()
193194

194195
def run(self) -> None:
195-
# Block until worker stops running.
196+
"""
197+
Processes tasks from the task queue.
198+
"""
196199
while self.running:
197-
sleep(0.05)
200+
if len(self.queue) == 0:
201+
# Nothing queued, so wait a bit.
202+
sleep(0.05)
203+
continue
204+
task = self.queue.pop()
205+
task._run()
198206

199207
def _process_input(self) -> None:
200208
while True:
@@ -214,10 +222,17 @@ def _process_input(self) -> None:
214222
case RequestType.EXECUTE:
215223
script = request.get("script")
216224
inputs = request.get("inputs")
225+
queue = request.get("queue")
217226
task = Task(uuid, script, inputs)
218227
self.tasks[uuid] = task
219-
task._thread = Thread(target=task._run, name=f"Appose-{uuid}")
220-
task._thread.start()
228+
if queue == "main":
229+
# Add the task to the main thread queue.
230+
self.queue.append(task)
231+
else:
232+
# Create a thread and save a reference to it, in case its script
233+
# kills the thread. This happens e.g. if it calls sys.exit.
234+
task._thread = Thread(target=task._run, name=f"Appose-{uuid}")
235+
task._thread.start()
221236

222237
case RequestType.CANCEL:
223238
task = self.tasks.get(uuid)

0 commit comments

Comments
 (0)