【问题标题】:Python multithreading/subprocess with functions具有函数的 Python 多线程/子进程
【发布时间】:2015-11-30 05:47:00
【问题描述】:

我想在后台执行两个命令,第二个在后台执行。

import time
loop =[ 1,100]
start_time_loop = time.time()
for in loop:
    print i
end_time_loop = time.time()

multi()
   start_time_func = time.time()
   c= 5*2
   end_time_func = time.time()

当乘法完成时,循环应该在后台运行。

我要证明:

start_time_loop < start_time_func
end_time_func << end_time_loop

任何指针都会有所帮助。

【问题讨论】:

  • Python 不能使用本机运行多个进程。查看线程模块。
  • Python 可以使用多个进程 - 这就是 multiprocessing 模块所做的。

标签: python multithreading python-3.x multiprocessing subprocess


【解决方案1】:

你需要使用多处理来做你想做的事。它基本上会在后台启动一个新的(克隆的)python 副本。

import time
from multiprocessing import Process


def thing_1():
    """We'll run this in a subprocess."""
    for i in range(10):
        print('thing_1: {}'.format(i))
        # let's make it take a bit longer
        time.sleep(1)


def thing_2():
    """We'll run this as a normal function in the current python process."""
    time.sleep(1)
    c = 5 * 2
    print('thing_2: {}'.format(c))
    # let's make this take a bit longer too
    time.sleep(1)



if __name__ == '__main__':
    # start the first thing running "in the background"
    p = Process(target=thing_1)
    p.start()
    # keep a record of when we started it running
    start_thing_1 = time.time()

    # let's run the other thing
    start_thing_2 = time.time()
    thing_2()
    end_thing_2 = time.time()

    # this will wait for the first thing to finish
    p.join()
    end_thing_1 = time.time()

    print('thing 1 took {}'.format(end_thing_1 - start_thing_1))
    print('thing 2 took {}'.format(end_thing_2 - start_thing_2))

最后你会看到:

thing 1 took 10.020239114761353
thing 2 took 2.003588914871216

因此,当thing_1 在后台运行时,您的本地python 可以继续执行其他操作。

您需要使用特殊机制在两个 python 副本之间传输任何信息。而且打印总是会有点奇怪,因为你真的不知道接下来要打印哪个 python 副本。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-10
    • 2014-12-19
    • 1970-01-01
    • 2021-07-16
    • 1970-01-01
    • 2014-09-28
    相关资源
    最近更新 更多