【发布时间】: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