如何在填充列表时运行线程?

时间:2018-04-19 17:34:04

标签: python python-3.x

目前,我正在使用这样的系统:

class Processor(object):
    """
    Makes sure that all operations the user requires to be processed are processed in order
    Also makes sure that the users are still pickle-able
    """
    def __init__(self):
        self.tasks = []
        self.killed = False

    def begin_processing(self):
        while not self.killed:
            if not self.tasks:
                pass 

游戏中的用户基本上将任务(基本上是threading.Timer)附加到tasks。该系统的要点是确保实际的用户对象是可选择的。

然而,这是非常低效的,因为它不断检查队列中是否有任何任务。

我宁愿这样做,以便它只在任务附加到队列时运行。有没有办法实现这个目标?

1 个答案:

答案 0 :(得分:1)

我认为你要找的是一条消息queue

import queue    

class Processor(object):
    """
    Makes sure that all operations the user requires to be processed are processed in order
    Also makes sure that the users are still pickle-able
    """
    def __init__(self):
        self.tasks = queue.Queue()
        self.killed = False

    def begin_processing(self):
        while not self.killed:
            task = self.tasks.get()