简体   繁体   English

我的HelloWorld队列是否正常工作?

[英]Is my HelloWorld queue working?

I'm about to put this design into use in an application, but I'm fairly new to threading and Queue stuff in python. 我打算在应用程序中使用这种设计,但是对于python中的线程和队列内容我还是很陌生。 Obviously the actual application is not for saying hello, but the design is the same - ie there is a process which takes some time to set-up and tear down, but I can do multiple tasks in one hit. 显然,实际的应用程序不是要打招呼,而是设计是相同的-即有一个过程需要花费一些时间进行设置和拆除,但我可以一次完成多个任务。 Tasks will arrive at random times, and often in bursts. 任务将在随机时间到达,并且通常会突然出现。

Is this a sensible and thread safe design? 这是明智且线程安全的设计吗?

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. The thread safety is handled by Queue implementation (also you must handle in your _say_hello implementation if it is required). 线程安全性由Queue实现处理(如果需要,您也必须在_say_hello实现中处理)。

  2. Burst handler problem: A burst should be handled by a single thread only.(ex: let's say your process setup/teardown takes 10 seconds; at second 1 all threads will be busy with burst from sec 0, on second 5 a new task(or burst) but no thread available to handle them/it). 突发处理程序问题:突发仅应由单个线程处理。(例如:假设您的进程设置/拆卸需要10秒;在秒1时,所有线程将从秒0开始忙于突发,在秒5中,新任务将忙于(或爆裂),但没有可用的线程来处理它们)。 So a burst should be defined by max number of tasks (or maybe "infinite") for a specific time-window. 因此,应通过特定时间窗的最大任务数(或“无限”)来定义突发。 An entry in queue should be a list of tasks. 队列中的条目应该是任务列表。

How can you group burst tasks list? 如何对突发任务列表进行分组? I provide a solution as code, more easy to explain ... 我提供了一个解决方案作为代码,更容易解释...

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)

If you want to have a maximum of messages in a burst, you just need to slice the available_tasks in multiple lists. 如果您希望突发中有最多的消息,则只需将available_tasks切片为多个列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么我的消费者在队列中与我的生产者分开工作? - Why is my consumer working separately from my producer in the queue? 改变我的python路径:helloworld.py返回未找到的命令 - - Altering my python path: helloworld.py returns command not found— 任务队列停止工作 - Task Queue stopped working 使用Tkinter,Progressbar和Queue - Working with Tkinter, Progressbar, and Queue 我试图从 clrs 书中实现队列,但它没有按预期工作? 我的代码有什么问题 - Im trying to implement queue from clrs book ,but its not working as expected ? whats wrong with my code 是什么导致我的链表队列python文件中的名称错误故障无法正常工作 - What is causing the name error fault in my linkedlist queue python file from working 为什么Aptana / Pydev在我的helloworld python代码中显示“打印”和“ __name__”的“未定义变量”错误? - Why is Aptana/Pydev showing “undefined variable” errors for “print” and “__name__” in my helloworld python code? 优先队列不适用于 Celery 和 RabbitMQ - Priority queue not working with Celery and RabbitMQ 芹菜任务队列不能与rabbitmq一起使用 - celery tasks queue not working with rabbitmq multiprocessing.Queue的工作示例 - working example of multiprocessing.Queue
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM