简体   繁体   中英

Communication queue between python threads not working

I'm trying to have an object that initiates a thread with a shared queue. The following is a representation of what I'm trying to achieve with it.

from multiprocessing import Queue
from queue import Empty
from threading import Thread


class thread_writer(Thread):
    def __init__(self, queue):
        super().__init__()
        self._write_queue = queue

    def run(self) -> None:
        idx = 0
        while True:
            self._write_queue.put(idx)
            idx += 1


class thread_reader:
    def __init__(self):
        self._read_queue = Queue()
        self._writer = thread_writer(self._read_queue)
        self._writer.run()

        while True:
            try:
                q_msg = self._read_queue.get()
                print(q_msg)
            except Empty():
                pass


if __name__ == '__main__':
    test = thread_reader()

Basically the writer Thread continuously writes to the queue, whereas the reader object initiates the thread and continuously reads from the Queue. However nothing gets printed. Any idea what I'm doing wrong here?

I get the following traceback when quitting the program:

Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "/home/daniel/Work/ss15m22_sw/sw_test/lib/test.py", line 23, in __init__
    self._writer.run()
  File "/home/daniel/Work/ss15m22_sw/sw_test/lib/test.py", line 14, in run
    self._write_queue.put(idx, )
  File "/usr/lib/python3.6/multiprocessing/queues.py", line 82, in put
    if not self._sem.acquire(block, timeout): 

The problem is you are calling run() method directly. call the start() method, which will call run() in a separate thread of control.

class thread_reader:
    def __init__(self):
        self._read_queue = Queue()
        self._writer = thread_writer(self._read_queue)
        self._writer.start() # changed

        while True:
            try:
                q_msg = self._read_queue.get()
                print(q_msg)
            except Empty():
                pass

From Python docs,

Once a thread object is created, its activity must be started by calling the thread's start() method. This invokes the run() method in a separate thread of control.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM