Skip to content

Commit 7d3a206

Browse files
authored
Create threaded_furkan_bulut.py
1 parent bae545f commit 7d3a206

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

Week07/threaded_furkan_bulut.py

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
import threading
2+
import time
3+
4+
def threaded(number_of_threads):
5+
"""
6+
A decorator to run a function in multiple threads.
7+
8+
:param number_of_threads: The number of threads to create for the function.
9+
:type number_of_threads: int
10+
:return: A wrapped function that runs in the specified number of threads.
11+
:rtype: function
12+
"""
13+
14+
def decorator_of_thread(func):
15+
"""
16+
Inner decorator to wrap the target function.
17+
18+
:param func: The function to be executed in multiple threads.
19+
:type func: function
20+
:return: The wrapped function with threading enabled.
21+
:rtype: function
22+
"""
23+
24+
def _wrapper(*args, **kwargs):
25+
"""
26+
Wrapper function to create, start, and synchronize threads.
27+
28+
:param args: Positional arguments to pass to the target function.
29+
:param kwargs: Keyword arguments to pass to the target function.
30+
:return: None
31+
:rtype: None
32+
"""
33+
threads = []
34+
for i in range(number_of_threads):
35+
threads.append(
36+
threading.Thread(
37+
target=func,
38+
args=args,
39+
kwargs=kwargs,
40+
name=f"Thread - {i}",
41+
)
42+
)
43+
for thread in threads:
44+
thread.start()
45+
for thread in threads:
46+
thread.join()
47+
48+
return _wrapper
49+
50+
return decorator_of_thread
51+
52+
53+
@threaded(16)
54+
def func(task_name):
55+
print(f"{threading.current_thread().name} is starting task: {task_name}")
56+
time.sleep(2)
57+
print(f"{threading.current_thread().name} has finished task: {task_name}")
58+
59+
60+
if __name__ == "__main__":
61+
func("Learning")

0 commit comments

Comments
 (0)