|
1 | 1 | import threading
|
2 | 2 |
|
3 |
| -""" |
4 |
| -threaded(n) |
5 |
| -============ |
6 |
| -
|
7 |
| -A decorator to run a function multiple times in parallel threads. |
8 |
| -
|
9 |
| -This decorator creates `n` threads to execute the decorated function. |
10 |
| -Each thread uses the same arguments and keyword arguments passed to the function. |
11 |
| -The main thread waits for all created threads to finish before continuing. |
12 |
| -
|
13 |
| -Parameters |
14 |
| ----------- |
15 |
| -n : int |
16 |
| - The number of threads to create for executing the function. |
17 |
| -
|
18 |
| -Notes |
19 |
| ------ |
20 |
| -- The function is executed `n` times, each in a separate thread. |
21 |
| -- Thread synchronization is handled using the `join()` method. |
22 |
| -""" |
23 |
| - |
24 | 3 | def threaded(n):
|
25 |
| - def decorator(func): |
26 |
| - def wrapper(*args, **kwargs): |
27 |
| - threads = [] |
28 |
| - for number in range(n): |
29 |
| - threads.append(threading.Thread(target=func, args=args, kwargs=kwargs)) |
30 |
| - |
31 |
| - for thread in threads: |
32 |
| - thread.start() |
33 |
| - |
34 |
| - for thread in threads: |
35 |
| - thread.join() |
36 |
| - return wrapper |
37 |
| - return decorator |
| 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) |
0 commit comments