Agent: Make thread name mandatory for creating daemon threads

This commit is contained in:
vakarisz 2022-03-09 16:55:22 +02:00
parent 83c25c6469
commit 7e6f1df3f5
2 changed files with 5 additions and 7 deletions

View File

@ -1,21 +1,21 @@
import logging import logging
from itertools import count from itertools import count
from threading import Event, Thread from threading import Event, Thread
from typing import Any, Callable, Iterable, Optional, Tuple from typing import Any, Callable, Iterable, Tuple
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
def run_worker_threads( def run_worker_threads(
target: Callable[..., None], target: Callable[..., None],
name_prefix: Optional[str] = None, name_prefix: str,
args: Tuple = (), args: Tuple = (),
num_workers: int = 2, num_workers: int = 2,
): ):
worker_threads = [] worker_threads = []
counter = run_worker_threads.counters.setdefault(name_prefix, count(start=1)) counter = run_worker_threads.counters.setdefault(name_prefix, count(start=1))
for i in range(0, num_workers): for i in range(0, num_workers):
name = None if name_prefix is None else f"{name_prefix}-{next(counter)}" name = f"{name_prefix}-{next(counter)}"
t = create_daemon_thread(target=target, name=name, args=args) t = create_daemon_thread(target=target, name=name, args=args)
t.start() t.start()
worker_threads.append(t) worker_threads.append(t)
@ -27,9 +27,7 @@ def run_worker_threads(
run_worker_threads.counters = {} run_worker_threads.counters = {}
def create_daemon_thread( def create_daemon_thread(target: Callable[..., None], name: str, args: Tuple = ()) -> Thread:
target: Callable[..., None], name: Optional[str] = None, args: Tuple = ()
) -> Thread:
return Thread(target=target, name=name, args=args, daemon=True) return Thread(target=target, name=name, args=args, daemon=True)

View File

@ -9,7 +9,7 @@ from infection_monkey.utils.threading import (
def test_create_daemon_thread(): def test_create_daemon_thread():
thread = create_daemon_thread(lambda: None) thread = create_daemon_thread(lambda: None, name="test")
assert thread.daemon assert thread.daemon