From df242619108bbdb9ad1ad97569b0856a3b1f8062 Mon Sep 17 00:00:00 2001 From: mertdoganaygun <163443178+mertdoganaygun@users.noreply.github.com> Date: Sun, 5 Jan 2025 17:44:09 +0300 Subject: [PATCH] =?UTF-8?q?threaded=5Fmert=5Fdo=C4=9Fan=5Fayg=C3=BCn.py?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...hreaded_mert_do\304\237an_ayg\303\274n.py" | 52 +++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 "Week07/threaded_mert_do\304\237an_ayg\303\274n.py" diff --git "a/Week07/threaded_mert_do\304\237an_ayg\303\274n.py" "b/Week07/threaded_mert_do\304\237an_ayg\303\274n.py" new file mode 100644 index 00000000..2c24bf39 --- /dev/null +++ "b/Week07/threaded_mert_do\304\237an_ayg\303\274n.py" @@ -0,0 +1,52 @@ +import threading + +def run_in_threads(thread_count): + """ + A decorator to execute a function concurrently in multiple threads. + + This decorator allows the decorated function to run `thread_count` times + concurrently in separate threads with the same arguments. + + Parameters + ---------- + thread_count : int + The number of threads to spawn for executing the function. + + Returns + ------- + ThreadManager + A decorator class that manages the thread lifecycle. + + Examples + -------- + >>> @run_in_threads(3) + ... def sample_task(data): + ... print(f"Processing: {data}") + ... + >>> sample_task("example") + Processing: example + Processing: example + Processing: example + + Notes + ----- + - Each thread runs the same function with the same parameters. + - The function waits for all threads to complete before proceeding. + - Return values from the threads are not captured. + """ + class ThreadManager: + def __init__(self, thread_count): + self.thread_count = thread_count + + def __call__(self, func): + def wrapper(*args, **kwargs): + threads = [] + for _ in range(self.thread_count): + thread = threading.Thread(target=func, args=args, kwargs=kwargs) + threads.append(thread) + for thread in threads: + thread.start() + for thread in threads: + thread.join() + return wrapper + return ThreadManager(thread_count)