Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 19 additions & 6 deletions fastapi_taskflow/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -236,14 +236,27 @@ def weakref_cb(_, q=self._work_queue):

num_threads = len(self._threads)
if num_threads < self._max_workers:
t = threading.Thread(
target=_cft._worker,
args=(
create_worker_context = getattr(self, "_create_worker_context", None)
worker_args: tuple[Any, ...]
if callable(create_worker_context):
worker_ctx = create_worker_context()
worker_args = (
weakref.ref(self, weakref_cb),
worker_ctx,
self._work_queue,
)
else:
worker_args = (
weakref.ref(self, weakref_cb),
self._work_queue,
self._initializer,
self._initargs,
),
getattr(self, "_initializer", None),
getattr(self, "_initargs", ()),
)

t = threading.Thread(
name=f"{self._thread_name_prefix or self}_{num_threads}",
target=_cft._worker,
args=worker_args,
)
t.daemon = True
t.start()
Expand Down
14 changes: 14 additions & 0 deletions tests/test_executor.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from fastapi_taskflow.executor import execute_task
from fastapi_taskflow.manager import _DaemonThreadPoolExecutor
from fastapi_taskflow.models import TaskConfig, TaskStatus
from fastapi_taskflow.store import TaskStore

Expand Down Expand Up @@ -41,6 +42,19 @@ def func(x, y, z=0):
assert captured == [(1, 2, 3)]


def test_daemon_thread_pool_executor_adjusts_without_initializer_attributes():
executor = _DaemonThreadPoolExecutor(max_workers=1)

for attr in ("_initializer", "_initargs"):
if hasattr(executor, attr):
delattr(executor, attr)

executor._adjust_thread_count()

assert len(executor._threads) == 1
executor.shutdown(wait=True, cancel_futures=True)


# ---------------------------------------------------------------------------
# Async tasks
# ---------------------------------------------------------------------------
Expand Down
Loading