【问题标题】:True Concurrency in PythonPython 中的真正并发
【发布时间】:2021-07-28 05:38:36
【问题描述】:

我对 Python 中的并发性比较陌生,我正在编写一些代码,这些代码必须在我的代码之外调用函数。我无法编辑这些函数,但我需要它们同时运行。我尝试了几种不同的解决方案,例如多处理、线程和 AsyncIO。如果我调用的每个函数都是用它定义的,那么 AsyncIO 最接近我想要的,但它们不是。

我正在调用的函数将阻塞。有时15-30分钟。在那段时间里,我需要其他功能来做其他事情。下面的代码说明了我的问题。如果你运行它,你会发现无论是使用线程还是多进程,任务总是串行运行。我需要它们同时运行。我知道输出会阻塞,直到整个脚本运行,但任务本身不应该。

我错过了什么?在 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)

【问题讨论】:

    标签: python multithreading concurrency multiprocessing python-asyncio


    【解决方案1】:

    请注意,您发布的程序导入了Thread,但从未使用它。

    更重要的是,在一行中:

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

    您正在调用 blockingfunc('Task1') 并将其返回的内容 (None) 作为 target 参数的值传递。完全不是你想要的。你的意图:

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

    然后,正如预期的那样,在您调用 start() 方法之前,实际上并没有调用 blockingfunc

    【讨论】:

    • 给这个人买啤酒!我已经盯着这段代码太久了,甚至没有看到我的 usethreads 函数没有调用线程。更重要的是,您对 Thread 和 Process 在运行函数和 args 中的方式的解释比我迄今为止读过的所有网页更有意义。感谢您快速简洁的回复。
    猜你喜欢
    • 2013-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-29
    • 1970-01-01
    • 2011-11-19
    • 2011-11-05
    • 1970-01-01
    相关资源
    最近更新 更多