使2个函数同时运行

时间:2010-06-02 11:16:48

标签: python multithreading parallel-processing

我试图让两个函数同时运行。

def func1():
    print 'Working'

def func2():
    print 'Working'

func1()
func2()

有谁知道怎么做?

9 个答案:

答案 0 :(得分:65)

这样做:

from threading import Thread

def func1():
    print 'Working'

def func2():
    print 'Working'

if __name__ == '__main__':
    Thread(target = func1).start()
    Thread(target = func2).start()

答案 1 :(得分:10)

The answer about threading很好,但你需要更具体地了解你想做什么。

如果你有两个使用大量CPU的功能,线程(在CPython中)可能会让你无处可去。然后你可能想看看multiprocessing module或者你可能想要使用jython / IronPython。

如果CPU绑定性能是原因,你甚至可以在(非线程)C中实现一些东西,并获得比在python中执行两个并行操作更大的加速。

如果没有更多信息,要想得到一个好的答案并不容易。

答案 2 :(得分:4)

一个选项,看起来它使两个函数在同一个运行 时间,正在使用threading模块(this答案中的示例)。

然而,它有一个小延迟,作为官方Python文档
page描述。尝试使用的更好的模块是multiprocessing

此外,还有其他Python模块可用于异步执行(两个代码同时工作)。有关它们的一些信息并帮助您选择一个,您可以阅读this Stack Overflow问题。

来自其他用户的关于threading模块

的评论
  

他可能想知道因为全球口译员锁   即使机器在中,它们也不会在同一时间执行   问题有多个CPU。 wiki.python.org/moin/GlobalInterpreterLock

- JonasElfströmJun 2 '10 at 11:39

来自文档的关于threading模块无法正常工作

的引用
  

CPython实现细节:在CPython中,由于Global Interpreter
  锁定,只有一个线程可以一次执行Python代码(即使是   某些面向性能的库可能会克服这种限制。)

     

如果您希望应用程序更好地利用多核机器的计算资源,建议您使用multiprocessing或concurrent.futures.ProcessPoolExecutor。
  但是,如果你是的话,线程仍然是一个合适的模型   想要同时运行多个I / O绑定任务。

答案 3 :(得分:2)

这可以通过Ray优雅地完成,该系统使您可以轻松地并行化和分发Python代码。

要并行化示例,您需要使用@ray.remote decorator定义函数,然后使用.remote调用它们。

import ray

ray.init()

# Define functions you want to execute in parallel using 
# the ray.remote decorator.
@ray.remote
def func1():
    print("Working")

@ray.remote
def func2():
    print("Working")

# Execute func1 and func2 in parallel.
ray.get([func1.remote(), func2.remote()])

如果func1()func2()返回结果,则需要将ray.get([func1.remote(), func2.remote()])替换为:

ret_id1 = func1.remote()
ret_id2 = func1.remote()
ret1, ret2 = ray.get([ret_id1, ret_id2])

使用Ray而不是multiprocessing模块或使用多线程有许多优点。特别是,相同的代码将在单台计算机以及多台计算机上运行。

有关Ray的更多优点,请参见this related post

答案 4 :(得分:1)

尝试一下

from threading import Thread

def fun1():
    print("Working1")
def fun2():
    print("Working2")

t1 = Thread(target=fun1)
t2 = Thread(target=fun2)

t1.start()
t2.start()

答案 5 :(得分:0)

与多进程不同,线程模块确实可以同时工作,但是计时有点差。下面的代码打印“ 1”和“ 2”。这些分别由不同的功能调用。我确实注意到,将它们打印到控制台时,它们的时序会稍有不同。

   from threading import Thread

   def one():
       while(1 == num):
           print("1")
           time.sleep(2)

   def two():
       while(1 == num):
           print("2")
           time.sleep(2)


   p1 = Thread(target = one)
   p2 = Thread(target = two)

   p1.start()
   p2.start()

输出:(请注意空格是打印之间的等待时间)

   1
   2

   2
   1

   12

   21

   12

   1
   2

不确定是否有纠正此问题的方法,或者根本不重要。就是我注意到的东西。

答案 6 :(得分:0)

我认为您要传达的内容可以通过多处理来实现。但是,如果要通过线程执行此操作,则可以执行此操作。 这可能有帮助

from threading import Thread
import time

def func1():
    print 'Working'
    time.sleep(2)

def func2():
    print 'Working'
    time.sleep(2)

th = Thread(target=func1)
th.start()
th1=Thread(target=func2)
th1.start()

答案 7 :(得分:0)

使用APscheduler进行测试:

from apscheduler.schedulers.background import BackgroundScheduler
import datetime

dt = datetime.datetime
Future = dt.now() + datetime.timedelta(milliseconds=2550)  # 2.55 seconds from now testing start accuracy

def myjob1():
    print('started job 1: ' + str(dt.now())[:-3])  # timed to millisecond because thats where it varies
    time.sleep(5)
    print('job 1 half at: ' + str(dt.now())[:-3])
    time.sleep(5)
    print('job 1 done at: ' + str(dt.now())[:-3])
def myjob2():
    print('started job 2: ' + str(dt.now())[:-3])
    time.sleep(5)
    print('job 2 half at: ' + str(dt.now())[:-3])
    time.sleep(5)
    print('job 2 done at: ' + str(dt.now())[:-3])

print(' current time: ' + str(dt.now())[:-3])
print('  do job 1 at: ' + str(Future)[:-3] + ''' 
  do job 2 at: ''' + str(Future)[:-3])
sched.add_job(myjob1, 'date', run_date=Future)
sched.add_job(myjob2, 'date', run_date=Future)

我得到了这些结果。证明它们正在同时运行。

 current time: 2020-12-15 01:54:26.526
  do job 1 at: 2020-12-15 01:54:29.072  # i figure these both say .072 because its 1 line of print code
  do job 2 at: 2020-12-15 01:54:29.072
started job 2: 2020-12-15 01:54:29.075  # notice job 2 started before job 1, but code calls job 1 first.
started job 1: 2020-12-15 01:54:29.076  
job 2 half at: 2020-12-15 01:54:34.077  # halfway point on each job completed same time accurate to the millisecond
job 1 half at: 2020-12-15 01:54:34.077
job 1 done at: 2020-12-15 01:54:39.078  # job 1 finished first. making it .004 seconds faster.
job 2 done at: 2020-12-15 01:54:39.091  # job 2 was .002 seconds faster the second test

答案 8 :(得分:0)

如果您还想等待直到两个功能都完成:

from threading import Thread

def func1():
    print 'Working'

def func2():
    print 'Working'

# Define the threads and put them in an array
threads = [
    Thread(target = self.func1),
    Thread(target = self.func2)
]

# Func1 and Func2 run in separate threads
for thread in threads:
    thread.start()

# Wait until both Func1 and Func2 have finished
for thread in threads:
    thread.join()