Skip to content

Commit f2d5953

Browse files
Create threaded_berke_alpaslan.py
1 parent bae545f commit f2d5953

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

Week07/threaded_berke_alpaslan.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
import threading
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+
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

0 commit comments

Comments
 (0)