我的HelloWorld队列工作吗?



我打算把这个设计应用到一个应用程序中,但是我对python中的线程和队列还是个新手。显然,实际的应用程序不是用来打招呼的,但设计是一样的——也就是说,有一个过程需要一些时间来设置和拆除,但我可以一次完成多个任务。任务会随机出现,而且经常是突然出现。

这是一个明智和线程安全的设计吗?

class HelloThing(object):
  def __init__(self):
    self.queue = self._create_worker()
  def _create_worker(self):
    import threading, Queue
    def worker():
      while True:
        things = [q.get()]
        while True:
          try:
            things.append(q.get_nowait())
          except Queue.Empty:
            break
        self._say_hello(things)
        [q.task_done() for task in xrange(len(things))]
    q = Queue.Queue()
    n_worker_threads = 1
    for i in xrange(n_worker_threads):
      t = threading.Thread(target=worker)
      t.daemon = True
      t.start()
    return q
  def _say_hello(self, greeting_list):
    import time, sys
    # setup stuff
    time.sleep(1)
    # do some things
    sys.stdout.write('hello {0}!n'.format(', '.join(greeting_list)))
    # tear down stuff
    time.sleep(1)

if __name__ == '__main__':
  print 'enter __main__'
  import time
  hello = HelloThing()
  hello.queue.put('world')
  hello.queue.put('cruel world')
  hello.queue.put('stack overflow')
  time.sleep(2)
  hello.queue.put('a')
  hello.queue.put('b')
  time.sleep(2)
  for i in xrange(20):
    hello.queue.put(str(i))
  #hello.queue.join()
  print 'finish __main__'
  1. 线程安全是由Queue实现处理的(如果需要,你也必须在你的_say_hello实现中处理)

  2. 突发处理程序问题:突发应该只由单个线程处理。(例如:假设您的流程设置/拆除需要10秒;在秒1时,所有线程都忙于从秒0开始的突发任务,在秒5时,一个新任务(或突发任务)出现,但没有线程可用来处理它们。因此,在一个特定的时间窗口内,burst应该由任务的最大数量(或者可能是"无限")来定义。队列中的条目应该是任务列表。

如何对突发任务列表进行分组?我提供了一个解决方案作为代码,更容易解释…

producer_q = Queue()
def _burst_thread():
   while True:
      available_tasks = [producer_q.get()]
      time.sleep(BURST_TIME_WINDOW)
      available_tasks.extend(producer_q.get() # I'm the single consumer, so will be at least qsize elements  
                             for i in range(producer_q.qsize()))
      consumer_q.push(available_tasks)

如果你想在一个突发事件中拥有最多的消息,你只需要在多个列表中切片available_tasks。

最新更新