Skip to content
Snippets Groups Projects
Commit 7dfa9524 authored by Piotr Maślanka's avatar Piotr Maślanka
Browse files

added functionality to `ThreadCollection`

parent 81f2a5e9
No related branches found
No related tags found
No related merge requests found
...@@ -3,4 +3,4 @@ ...@@ -3,4 +3,4 @@
* more time-related calls will accept time strings * more time-related calls will accept time strings
* added optional `delay` argument to `call_in_separate_thread` * added optional `delay` argument to `call_in_separate_thread`
* beefed up BogusTerminableThread docs * beefed up BogusTerminableThread docs
* added `ThreadCollection.add` * added functionality to `ThreadCollection`
__version__ = '2.14.47a3' __version__ = '2.14.47a4'
import threading
import typing as tp import typing as tp
from threading import Thread from threading import Thread
...@@ -15,10 +16,36 @@ class ThreadCollection: ...@@ -15,10 +16,36 @@ class ThreadCollection:
>>> tc.start() >>> tc.start()
>>> tc.terminate() >>> tc.terminate()
>>> tc.join() >>> tc.join()
This also implements iteration (it will return all the threads in the collection) and
length check.
""" """
__slots__ = ('threads', ) __slots__ = ('threads', )
def __len__(self):
return len(self.threads)
def __iter__(self):
return iter(self.threads)
@classmethod
def get_currently_running(cls, include_main_thread: bool = True) -> 'ThreadCollection':
"""
Get all currently running threads as thread collection
:param include_main_thread: whether to include the main thread
:return: a thread collection representing all currently running threads
"""
result = []
for thread in threading.enumerate():
# noinspection PyProtectedMember
if not include_main_thread and isinstance(thread, threading._MainThread):
continue
result.append(thread)
return ThreadCollection(result)
@classmethod @classmethod
def from_class(cls, cls_to_use, iteratable, **kwargs) -> 'ThreadCollection': def from_class(cls, cls_to_use, iteratable, **kwargs) -> 'ThreadCollection':
""" """
...@@ -46,6 +73,14 @@ class ThreadCollection: ...@@ -46,6 +73,14 @@ class ThreadCollection:
def __init__(self, threads: tp.Sequence[Thread]): def __init__(self, threads: tp.Sequence[Thread]):
self.threads = list(threads) self.threads = list(threads)
def append(self, thread: Thread) -> None:
"""
Alias for :meth:`~satella.coding.concurrent.ThreadCollection.add`
:param thread: thread to add
"""
self.add(thread)
def add(self, thread: Thread) -> None: def add(self, thread: Thread) -> None:
""" """
Add a thread to the collection Add a thread to the collection
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment