q = Queue() で初期化した後は、qでやり取りしていますね。
import time from queue import Queue from threading import Thread, current_thread class Worker(Thread): def __init__(self, queue: Queue, id: int): super().__init__(name=str(id)) self.queue = queue def run(self) -> None: while not self.queue.empty(): item = self.queue.get() print(f"Thread {current_thread().name}: " f"processing item {item} from the queue") time.sleep(2) def main(thread_num: int) -> None: q = Queue() for i in range(10): q.put(i) threads = [] for i in range(thread_num): thread = Worker(q, i + 1) thread.start() threads.append(thread) for thread in threads: thread.join() if __name__ == "__main__": thread_num = 4 main(thread_num)
$ python3 message_queue.py
Thread 1: processing item 0 from the queue
Thread 2: processing item 1 from the queue
Thread 3: processing item 2 from the queue
Thread 4: processing item 3 from the queue
Thread 2: processing item 4 from the queue
Thread 3: processing item 5 from the queue
Thread 1: processing item 6 from the queue
Thread 4: processing item 7 from the queue
Thread 3: processing item 8 from the queue
Thread 2: processing item 9 from the queue