简体   繁体   English

在 python 中并行运行多个函数

[英]Run multiple functions parallelly in python

Ok so, I searched for this answer all over the inte.net but I am getting the answers which just run these functions one after the other好吧,我在整个 inte.net 上搜索了这个答案,但我得到的答案只是一个接一个地运行这些函数

import time

def a():
    time.sleep(5)
    print("lmao")
def b():
    time.sleep(5)
    print("not so lmao huh")

I want "lmao" and "not so lmao" to be printed at the same time ( after 5 seconds) The solutions which I saw all over the inte.net just printed "lmao" after 5 seconds of starting the program and "not so lmao huh" after 5 seconds of a()我希望同时打印“lmao”和“not so lmao”(5 秒后) 我在整个 inte.net 上看到的解决方案在启动程序 5 秒后打印“lmao”和“not so” lmao huh" 在a() 5 秒后

As Far as i understood your question you should use threading for it.据我了解你的问题,你应该为它使用线程。 you can refer this guideThreading .您可以参考本指南Threading If you need any clarification feel free to comment.如果您需要任何说明,请随时发表评论。

import thread
import time

# Define a function for the thread
def print_time( threadName, delay):
   count = 0
   while count < 5:
      time.sleep(delay)
      count += 1
      print "%s: %s" % ( threadName, time.ctime(time.time()) )

# Create two threads as follows
try:
   thread.start_new_thread( print_time, ("Thread-1", 2, ) )
   thread.start_new_thread( print_time, ("Thread-2", 4, ) )
except:
   print "Error: unable to start thread"

while 1:
   pass

If you want to run your functions parallel, then you may want to use the multiprocessing .如果你想并行运行你的函数,那么你可能想要使用multiprocessing

You can create some processes and execute your function in them.您可以创建一些进程并在其中执行您的 function。

For example:例如:

import time
import multiprocessing as mp
from multiprocessing.context import Process


def a():
    time.sleep(5)
    print("lmao")


def b():
    time.sleep(5)
    print("not so lmao huh")

if __name__ == '__main__':
    p1: Process = mp.Process(target=a)
    p2: Process = mp.Process(target=b)
    p1.start()
    p2.start()
    p1.join()
    p2.join()

There are also such API for coroutines and tasks and threading .还有这样的 API 用于coroutines 和 tasksthreading Maybe you will find them more convenient.也许你会发现它们更方便。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM