簡體   English   中英

Python,使用多處理線程

[英]Python, using threading with multiprocessing

有人可以解釋為什么線程在 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 循環,這會白白占用大量資源。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM