Ale*_*x L 5 python multithreading timer
我试图每秒运行三个函数(每个函数最多需要1秒执行).然后,我想存储每个函数的输出,并将它们写入单独的文件.
目前我正在使用Timers进行延迟处理.(我可以继承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)
Run Code Online (Sandbox Code Playgroud)
处理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])
Run Code Online (Sandbox Code Playgroud)
思考?
编辑:添加我自己的答案作为可能性
我相信python Queue模块正是为这种情况而设计的.你可以做这样的事情,例如:
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))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
966 次 |
| 最近记录: |