Hello World

mail@pastecode.io avatar
unknown
python
9 days ago
1.4 kB
0
Indexable
Never
# Import necessary libraries
import multiprocessing
import threading
import time
import queue
import os

# Define constants
NUM_WORKERS = 4
TASK_QUEUE = queue.Queue()

def string_builder():
    """
    Joins the text "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 = 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__":
    # Give time for the computer to think
    time.sleep(1)
    main()
Leave a Comment