每秒运行多个函数,并将结果写入文件
我想每秒运行三个函数(每个函数最多执行1秒)。然后我想把每个函数的输出存储起来,并写入不同的文件。
目前我在用Timer
来处理延迟。(我可以创建一个Thread
的子类,但这样对这个简单的脚本来说有点复杂)
def main:
for i in range(3):
set_up_function(i)
t = Timer(1, run_function, [i])
t.start()
time.sleep(100) # Without this, main thread exits
def run_function(i):
t = Timer(1, run_function, [i])
t.start()
print function_with_delay(i)
处理function_with_delay
的输出最好的方法是什么?是把每个函数的结果添加到一个全局列表里吗?
然后我可以在主函数的最后加上这样的代码:
...
while True:
time.sleep(30) # or in a try/except with a loop of 1 second sleeps so I can interrupt
for i in range(3):
save_to_disk(data[i])
有什么想法吗?
编辑:添加了我自己的答案作为一种可能性
3 个回答
0
另一种选择是实现一个类(参考这个回答),它使用了threading.Lock()
。这样做的好处是可以在ItemStore
上等待,而save_to_disk可以使用getAll
,而不是一直去检查队列。(对于大数据集来说,这样可能更高效?)
这种方法特别适合在固定的时间间隔内写入数据(比如每30秒写一次),而不是每秒写一次。
class ItemStore(object):
def __init__(self):
self.lock = threading.Lock()
self.items = []
def add(self, item):
with self.lock:
self.items.append(item)
def getAll(self):
with self.lock:
items, self.items = self.items, []
return items
1
我建议你存一个列表的列表,里面包含两个东西:一个是布尔值(bool
),表示这个函数是否已经运行完;另一个是字符串(str
),就是函数的输出结果。每个函数在添加输出的时候,用一个互斥锁来锁定这个列表(如果你不在乎线程安全,可以不使用这个锁)。然后,设置一个简单的循环,检查所有的bool
值是否都是True
,如果都是,那就可以进行save_to_disk
的操作了。
6
我认为Python的队列模块就是为了这种情况而设计的。你可以这样做,比如:
def main():
q = Queue.Queue()
for i in range(3):
t = threading.Timer(1, run_function, [q, i])
t.start()
while True:
item = q.get()
save_to_disk(item)
q.task_done()
def run_function(q, i):
t = threading.Timer(1, run_function, [q, i])
t.start()
q.put(function_with_delay(i))