gpt4 book ai didi

Python,将线程与多处理一起使用

转载 作者:太空宇宙 更新时间:2023-11-04 05:23:25 24 4
gpt4 key购买 nike

有人可以解释为什么线程在 multiprocessing.Process 中不起作用。

我附上了一些例子来解释我的问题。

我有一个进程每秒执行一次并写入文件。当我从 shell 运行它时,它按预期工作。

stat_collect.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from threading import Timer
from os import path
from datetime import datetime

STAT_DATETIME_FMT = '%Y-%m-%d %H:%M:%S'


def collect_statistics():
my_file = 'test.file'
if not path.exists(my_file):
with open(my_file, 'w') as fp:
fp.write(datetime.now().strftime(STAT_DATETIME_FMT) + '\n')
else:
with open(my_file, 'a') as fp:
fp.write(datetime.now().strftime(STAT_DATETIME_FMT) + '\n')

Timer(1, collect_statistics).start()


if __name__ == '__main__':
collect_statistics()

当我尝试从其他脚本运行它时(在后台工作):

#!/usr/bin/env python

from multiprocessing import Process
from stat_collect import collect_statistics # logger sc

if __name__ == '__main__':
# This don't work
p = Process(target=collect_statistics)
p.start()

while True:
pass

方法 collect_statistics 只执行一次,但如果我使用 Thread(target=collect_statistics).start() 它就像我从 shell 运行它一样工作。为什么会这样?

最佳答案

事情是这样的:

  1. 你开始你的过程
  2. collect_statistics 运行
  3. 计时器启动
  4. 现在流程中调用的函数(collect_statistics) 已经完成,所以流程退出,同时终止计时器。

修复方法如下:

stat_collect.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from threading import Timer
from os import path
from datetime import datetime
import time

STAT_DATETIME_FMT = '%Y-%m-%d %H:%M:%S'


def collect_statistics():
while True:
my_file = 'test.file'
if not path.exists(my_file):
with open(my_file, 'w') as fp:
fp.write(datetime.now().strftime(STAT_DATETIME_FMT) + '\n')
else:
with open(my_file, 'a') as fp:
fp.write(datetime.now().strftime(STAT_DATETIME_FMT) + '\n')

time.sleep(1)


if __name__ == '__main__':
collect_statistics()

对于调用脚本:

#!/usr/bin/env python

from multiprocessing import Process
from stat_collect import collect_statistics # logger sc

if __name__ == '__main__':
# This don't work
p = Process(target=collect_statistics)
p.start()
p.join() # wait until process is over, e.g forever

p.join() 只是在这里代替你无限的 while 循环,它白白占用了很多资源。

关于Python,将线程与多处理一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39572941/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com