File tree 1 file changed +52
-0
lines changed
1 file changed +52
-0
lines changed Original file line number Diff line number Diff line change
1
+ import threading
2
+
3
+ def threaded (n ):
4
+ """Creates a decorator that runs the decorated function in multiple threads.
5
+
6
+ This decorator creates `n` threads to execute the decorated function concurrently.
7
+ Each thread runs the same function with the same arguments. All threads are started
8
+ and then joined before returning.
9
+
10
+ Parameters
11
+ ----------
12
+ n : int
13
+ Number of threads to create and run the function in
14
+
15
+ Returns
16
+ -------
17
+ Threaded
18
+ A decorator class that handles the thread creation and management
19
+
20
+ Examples
21
+ --------
22
+ >>> @threaded(3)
23
+ ... def example_function(x):
24
+ ... print(f"Processing {x}")
25
+ ...
26
+ >>> example_function("test")
27
+ Processing test
28
+ Processing test
29
+ Processing test
30
+
31
+ Notes
32
+ -----
33
+ - All threads execute the same function with identical arguments
34
+ - The decorator waits for all threads to complete before returning
35
+ - No return values are captured from the threaded function executions
36
+
37
+ """
38
+ class Threaded :
39
+ def __init__ (self , n ):
40
+ self .n = n
41
+ def __call__ (self , func ):
42
+ def wrapper (* args , ** kwargs ):
43
+ threads = []
44
+ for i in range (self .n ):
45
+ t = threading .Thread (target = func , args = args , kwargs = kwargs )
46
+ threads .append (t )
47
+ for t in threads :
48
+ t .start ()
49
+ for t in threads :
50
+ t .join ()
51
+ return wrapper
52
+ return Threaded (n )
You can’t perform that action at this time.
0 commit comments