Skip to content

Commit 33115ea

Browse files
Merge pull request #52 from codejunction/main
added multi threading utility for python
2 parents 8d904d8 + 6f352cf commit 33115ea

File tree

3 files changed

+77
-0
lines changed

3 files changed

+77
-0
lines changed

Python Multithreading/app.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
from threadutility import ThreadRipper
2+
from loguru import logger
3+
from random import randint
4+
import time
5+
6+
7+
NUMBER_OF_JOBS = 100
8+
9+
10+
def my_job(number: int, delay: int):
11+
time.sleep(delay)
12+
logger.info(f"{number}")
13+
return f"Input Number : {number} | Delay : {delay}"
14+
15+
16+
if __name__ == "__main__":
17+
threading_helper: ThreadRipper = ThreadRipper(
18+
n_threads=10, thread_name_prefix="my_job"
19+
)
20+
21+
for i in range(NUMBER_OF_JOBS):
22+
threading_helper.add_executables(my_job, i, randint(1, 5))
23+
24+
threading_helper.start()
25+
26+
logger.info(threading_helper.result)
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
loguru
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
from typing import Callable, Any
2+
from functools import partial
3+
import concurrent.futures
4+
from loguru import logger
5+
6+
7+
class ThreadRipper(object):
8+
def __init__(self, n_threads: int = 4, thread_name_prefix: str = "TRip") -> None:
9+
"""Executes a series of partial functions in multithreading.
10+
11+
Args:
12+
n_threads (int): number of threads
13+
thread_name_prefix (str, optional): thread prefix name. Defaults to "TRip".
14+
Usage:
15+
_tr = ThreadRipper(60)
16+
for i in range(500):
17+
_tr.add_executables(callable_function, d=i, i=1)
18+
_tr.start()
19+
print(_tr.result) # to get the collated result
20+
21+
"""
22+
23+
self.__thread_name_prefix = thread_name_prefix
24+
self.__partials = []
25+
self.__thread_count = n_threads
26+
self.__futures = []
27+
28+
def add_executables(self, func: Callable, *fargs: Any, **fkwargs: Any):
29+
self.__partials.append(partial(func, *fargs, **fkwargs))
30+
31+
def start(self):
32+
logger.info(
33+
f"Dispatching ThreadPoolExecutor with {self.__thread_count} threads(s)"
34+
)
35+
with concurrent.futures.ThreadPoolExecutor(
36+
self.__thread_count, thread_name_prefix=self.__thread_name_prefix
37+
) as executor:
38+
_res = []
39+
for executable in self.__partials:
40+
_res.append(executor.submit(executable))
41+
executor.shutdown(wait=False)
42+
self.__futures = [i.result() for i in _res]
43+
44+
@property
45+
def result(self):
46+
try:
47+
return self.__futures
48+
finally:
49+
self.__partials = []
50+
self.__futures = []

0 commit comments

Comments
 (0)