簡體   English   中英

Python 中的真正並發

[英]True Concurrency in Python

我對 Python 中的並發性比較陌生,我正在處理一些必須在我的代碼之外調用函數的代碼。 我無法編輯這些函數,但我需要它們同時運行。 我嘗試了幾種不同的解決方案,例如多處理、線程和 AsyncIO。 如果我調用的每個 function 都是用它定義的,那么 AsyncIO 最接近我想要的,但它們不是。

我正在調用的函數將阻塞。 有時15-30分鍾。 在那段時間里,我需要其他功能來做其他事情。 下面的代碼說明了我的問題。 如果你運行它,你會發現無論是使用線程還是多進程,任務總是串行運行。 我需要它們同時運行。 我知道 output 會阻塞,直到整個腳本運行,但任務本身不應該。

我錯過了什么? 在 Python 中有如此多的並發選擇或至少明顯的並發選擇,我認為這比我找到的要容易。

#!/usr/bin/python3

from datetime import datetime
from multiprocessing import Process
import sys
from threading import Thread
from time import sleep


def main():

    # Doing it with the multiprocess module
    print("Using MultiProcess:")
    useprocs()

    print("\nUsing Threading:")
    usethreads()


def useprocs():
    procs = []
    
    task1 = Process(target=blockingfunc('Task1'))
    task1.start()
    procs.append(task1)

    task2 = Process(target=blockingfunc('Tast2'))
    task2.start()
    procs.append(task2) 

    task1.join()
    task2.join()
    
    print('All processes completed')


def usethreads():
    threads = []

    task3 = Process(target=blockingfunc('Task3'))
    task3.start()
    threads.append(task3)

    task4 = Process(target=blockingfunc('Task4'))
    task4.start()
    threads.append(task4)   

    task3.join()
    task4.join()

    print('All threads completed')


def blockingfunc(taskname):
    now = datetime.now()
    current_time = now.strftime("%H:%M:%S")
    print(current_time, "Starting task: ", taskname)
    sleep(5)
    now = datetime.now()
    current_time = now.strftime("%H:%M:%S")
    print(current_time, taskname, "completed")


if __name__ == '__main__':
    try:
        main()
    except:
        sys.exit(1)

請注意,您發布的程序會導入Thread但從不使用它。

更重要的是,在一行中:

task1 = Process(target=blockingfunc('Task1'))

您正在調用blockingfunc('Task1')並將它返回的內容( None )作為target參數的值傳遞。 完全不是你想要的。 你的意圖:

task1 = Process(target=blockingfunc, args=['Task1'])

然后,正如預期的那樣, blockingfunc在您調用start()方法之前實際上並沒有被調用。

暫無
暫無

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

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