简体   繁体   中英

Python Thread with Queue

i try to get working python thread with queue. But when i put any value to queue i cannt find this value in other thread.

from Queue import Queue
from threading import Thread
import time
class ThreadWorker(object):
    verbose = True
    thread = None
    queue = Queue()

    def __init__(self, workerId, queueMaxSize = 50, emptyQueuewaitTime = 1):
        self.queue.maxsize = queueMaxSize
        self.thread = Thread(target=self.__work, args=(workerId, emptyQueuewaitTime))
        self.thread.setDaemon(True)
        self.thread.start()

    def __work(self, workerId, sl):
        while(True):
            if self.queue.empty:
                print '[THREAD_WORKER] id: {}, EMPTY QUEUE sleeping: {}'.format(workerId, sl)
                time.sleep(sl) 
                continue
            if self.verbose:
                print '[THREAD_WORKER] id: {}, queueSize: {}'.format(workerId, self.queue.qsize())
            d = self.queue.get()
            self.queue.task_done()

    def put(self, item, waitIfFull = True):
        self.queue.put(item, waitIfFull)
        if self.verbose:
            print "Add to queue, current queue size: {}".format(self.queue.qsize())

Create instance and fill the queue ...

t = ThreadWorker("t1")
t.put("item1")
t.put("item2")
t.put("item3")

Output from thread with name t1 is: [THREAD_WORKER] id: t1, EMPTY QUEUE sleeping: 1

But in queue are three items ....

queue.empty is a method; you need to call it. That's the immediate issue.

If you create two ThreadWorkers, you're going to find that they're sharing their queue s. Unlike other languages, an assignment like queue = Queue() at class level doesn't declare an instance variable; it declares a class attribute. To create an instance attribute, you would instead assign self.queue = Queue() in the __init__ method. There is no need for any sort of declaration of this attribute's existence at class level.

Finally, checking whether a Queue is empty is very prone to race conditions, since whether or not it's empty might change between empty() and get() . It's generally better to just call get , and let get wait for a put if the queue is empty.

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