Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/git/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使两个函数同时运行_Python_Multithreading_Parallel Processing - Fatal编程技术网

Python 使两个函数同时运行

Python 使两个函数同时运行,python,multithreading,parallel-processing,Python,Multithreading,Parallel Processing,我试图使两个函数同时运行 def func1(): print 'Working' def func2(): print 'Working' func1() func2() 有人知道怎么做吗?这样做: from threading import Thread def func1(): print('Working') def func2(): print("Working") if __name__ == '__main__': Thread(

我试图使两个函数同时运行

def func1():
    print 'Working'

def func2():
    print 'Working'

func1()
func2()
有人知道怎么做吗?

这样做:

from threading import Thread

def func1():
    print('Working')

def func2():
    print("Working")

if __name__ == '__main__':
    Thread(target = func1).start()
    Thread(target = func2).start()
这很好,但你需要更具体地说明你想做什么

如果您有两个函数都使用了大量CPU,那么线程(在CPython中)可能会让您一事无成。然后,您可能想看看,或者可能想使用jython/IronPython

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


如果没有更多的信息,很难找到一个好的答案。

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

但是,作为官方Python文档,它有一点延迟
描写。可以尝试使用的更好的模块是

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

其他用户对
线程化
模块的评论

由于全局解释器锁,他可能想知道这一点
即使机器处于
问题有多个CPU

-乔纳斯·埃尔夫斯特伦

引用文档中有关
线程化
模块不工作的内容
CPython实现细节:在CPython中,由于全局解释器
锁定,一次只能有一个线程执行Python代码(即使
某些面向性能的库可能会克服此限制)

如果您希望应用程序更好地利用多核计算机的计算资源,建议您使用多处理或并发.futures.ProcessPoolExecutor。
但是,如果您
要同时运行多个I/O绑定任务


试试这个

from threading import Thread

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

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

t1.start()
t2.start()

与多进程不同,线程模块可以同时工作,但计时有点不准确。下面的代码打印“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()
输出:(注意,该空间用于打印之间的等待)


不确定是否有办法纠正这一点,或者它是否有任何意义。这正是我注意到的。

我认为您想要传达的信息可以通过多重处理来实现。但是,如果您想通过线程执行,您可以这样做。 这可能会有帮助

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()

这可以通过一个允许您轻松并行化和分发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有许多优点。特别是,相同的代码将在一台机器以及一组机器上运行


有关Ray的更多优点,请参见。

使用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

他可能想知道,由于全局解释器锁,即使机器有多个CPU,它们也不会同时执行@joaquin——你说得对,很抱歉,复制粘贴后忘记取出函数执行。当函数返回某些内容时,如何获取结果?没有理由使用两个导入语句。只使用第二个。如何为函数提供参数?在每个print()函数的末尾可能重复I append time.time(),并将另一个答案的代码循环次数限制为9次。这是我在终端中看到的:('a',1509314761.857559)('a',1509314761.857664)('a',1509314761.85767)('a',1509314761.857675)('a',1509314761.85768)('a',1509314761.857685)('a',1509314761.85769)('a',1509314761.857695)('a',1509314761.857699)('b',1509314761.858138)('b',1509314761.858229)('('b',1509314761.858234)('b',1509314761.858239)('b',1509314761.858244)('b',1509314761.858249)('b',1509314761.858253)('b',1509314761.858258)即使使用多处理,它也不是真正的并发rite?一个接一个地运行。@weewefwqg3检查我回答中有关模块详细信息的链接。你也可以检查自己,但官方文档应该解释。Idk如果它是一个bug,但对我来说多处理不起作用。行
thr1=Process(target=run_foo(),args=())
本来不应该创建线程的(因为我没有运行
thr1.start()
)实际上创建了它,因此应该由
run\u foo()启动的进程
窃取执行,因此没有多线程。添加一个洞察,了解这如何解决OP的要求如何使用return语句实现这一点,它只有在函数具有print时才起作用
 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