Hello World App
unknown
python
a year ago
1.5 kB
3
Indexable
# Import necessary libraries import multiprocessing import threading import time import queue import os # Define constants NUM_WORKERS = 4 TASK_QUEUE = queue.Queue() def complex_string_builder(): # Imagine this function performs a complex operation to create "hello world" return ''.join(['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']) def worker(task_queue, result_queue): while not task_queue.empty(): task = task_queue.get() if task == "build_string": result = complex_string_builder() result_queue.put(result) task_queue.task_done() def main_process(result_queue): while True: try: result = result_queue.get(timeout=1) if result == "hello world": print(result) os._exit(0) except queue.Empty: pass def main(): # Populate task queue for _ in range(NUM_WORKERS): TASK_QUEUE.put("build_string") # Create result queue result_queue = queue.Queue() # Start worker threads for _ in range(NUM_WORKERS): threading.Thread(target=worker, args=(TASK_QUEUE, result_queue)).start() # Start main process in a separate thread threading.Thread(target=main_process, args=(result_queue,)).start() # Wait for all tasks to be completed TASK_QUEUE.join() if __name__ == "__main__": # Simulate a delay in the main process to make things more complicated time.sleep(1) main()
Editor is loading...
Leave a Comment