File tree Expand file tree Collapse file tree 1 file changed +51
-0
lines changed
Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Original file line number Diff line number Diff line change 1+ import threading
2+
3+ def threaded (n :int ) -> callable :
4+ """
5+ A decorator that runs a function using multiple threads.
6+
7+ :param n: Number of threads to create
8+ :type n: int
9+ :return: A decorator function for threading
10+ :rtype: function
11+ """
12+ # if n < 1 or not isinstance(n, int):
13+ # raise ValueError("Not Valid call of the decorator")
14+
15+ def decorator (func :callable ) -> callable :
16+ """
17+ An inner decorator function that wraps the original function with threads.
18+
19+ :param func: The original function to be run in threads
20+ :type func: function
21+ :return: A wrapper function that runs with threads
22+ :rtype: function
23+ """
24+ if not hasattr (func , "__call__" ):
25+ raise ValueError ("Not Valid Function" )
26+
27+ def wrapper (* args , ** kwargs )-> None :
28+ """
29+ A wrapper function that runs the function with multiple threads.
30+
31+ :param args: Positional arguments to pass to the function
32+ :param kwargs: Keyword arguments to pass to the function
33+ """
34+
35+ all_threads = []
36+ try :
37+ for _ in range (n ):
38+
39+ one_thread = threading .Thread (target = func , args = args , kwargs = kwargs )
40+ all_threads .append (one_thread )
41+ one_thread .start ()
42+
43+ for thread in all_threads :
44+ thread .join ()
45+
46+ except threading .ThreadError as te :
47+ print (te )
48+
49+ return wrapper
50+
51+ return decorator
You can’t perform that action at this time.
0 commit comments