Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/fortran/2.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_Python Multithreading - Fatal编程技术网

Python 两个函数的并行执行

Python 两个函数的并行执行,python,python-multithreading,Python,Python Multithreading,在Python中,如何执行两个时间间隔相差5秒的函数,直到计时器停止使用线程 e、 g: 尝试使用多处理 def you_function1(*args, **kwargs): pass def you_function2(*args, **kwargs): pass from multiprocessing import Process first_process = Process(target=you_function1) second_process = Proc

在Python中,如何执行两个时间间隔相差5秒的函数,直到计时器停止使用线程

e、 g:


尝试使用多处理

def you_function1(*args, **kwargs):
    pass

def you_function2(*args, **kwargs):
    pass

from multiprocessing import Process

first_process = Process(target=you_function1)

second_process = Process(target=you_function2)

first_process.start()

second_process.start()

first_process.join()
second_process.join()

对于这一点,线程化非常简单:

import threading
import time

def first_func():
    while True:
        print("First function",time.time()-start)
        time.sleep(10)

def second_func():
    time.sleep(5)
    while True:
        print("Second function",time.time()-start)
        time.sleep(10)

start = time.time()
t1 = threading.Thread(target=first_func)
t1.start()
t2 = threading.Thread(target=second_func)
t2.start()
输出:

First function 0.0
Second function 5.008664846420288
First function 10.002728939056396
Second function 15.010392904281616
First function 20.018056869506836
Second function 25.02572202682495

阅读线程模块,这里有很多例子和教程。我知道线程,但是如果他想更快地工作-这是必要的处理而不是线程,记住关于Gil,多处理可能非常低效或不可行,这取决于OP想要做什么。例如,如果这些线程正在监视进程空间中的对象,则子进程甚至无法工作。睡眠5秒钟意味着GIL不是问题。
First function 0.0
Second function 5.008664846420288
First function 10.002728939056396
Second function 15.010392904281616
First function 20.018056869506836
Second function 25.02572202682495