Skip to content

Commit bf0ef4e

Browse files
authored
Merge pull request #789 from Furk4nBulut/master
Create threaded_furkan_bulut.py
2 parents bb8f7da + c16f57e commit bf0ef4e

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

Week07/threaded_furkan_bulut.py

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
import threading
2+
import time
3+
4+
def threaded(number_of_threads):
5+
class Threaded:
6+
"""
7+
A class that acts as a decorator to run a function concurrently using multiple threads.
8+
9+
:param number_of_threads: The number of threads to spawn to run the decorated function.
10+
:type number_of_threads: int
11+
"""
12+
def __init__(self, number_of_threads):
13+
"""
14+
Initializes the Threaded class with the specified number of threads.
15+
16+
:param number_of_threads: Number of threads to use for the decorated function.
17+
:type number_of_threads: int
18+
"""
19+
self.number_of_threads = number_of_threads
20+
21+
def __call__(self, func):
22+
"""
23+
Makes the class instance callable and acts as a decorator for the provided function.
24+
25+
:param func: The function to be executed in multiple threads.
26+
:type func: function
27+
28+
:return: The wrapper function that creates threads and runs the decorated function.
29+
:rtype: function
30+
"""
31+
def wrapper(*args, **kwargs):
32+
"""
33+
Wrapper function that creates threads and runs the decorated function.
34+
35+
:param args: Positional arguments to pass to the decorated function.
36+
:type args: tuple
37+
38+
:param kwargs: Keyword arguments to pass to the decorated function.
39+
:type kwargs: dict
40+
"""
41+
threads = []
42+
43+
for i in range(self.number_of_threads):
44+
thread = threading.Thread(target=func, args=args, kwargs=kwargs, name=f"Thread-{i}")
45+
threads.append(thread)
46+
thread.start()
47+
48+
for thread in threads:
49+
thread.join()
50+
51+
return wrapper
52+
53+
return Threaded(number_of_threads)

0 commit comments

Comments
 (0)