Skip to main content
 首页 » 编程设计

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

2025年04月02日8pander-it

有人可以解释为什么线程在 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 循环,它白白占用了很多资源。