python - 如何使用 Python 3 的多处理池运行 2 个不同的函数?

标签 python multithreading asynchronous multiprocessing

好的,假设我有这个代码:

import time

def helloworld(sleep_time):
    while True:
        time.sleep(sleep_time)
        print('Hello world!')

def hellocountry():
    while True:
        time.sleep(60)
        print('Hello country!')

if __name__ == '__main__':
    with Pool(3) as p:
        p.map(helloworld, [1, 5, 7])

当 helloworld 正在执行时,我将如何执行 hellocountry?我想我可以编写一个包装函数,但这看起来相当笨拙且不符合Python风格。

最佳答案

只需使用 apply_async方法。

if __name__ == '__main__':
    with Pool(3) as p:
        p.apply_async(hellocountry)
        p.map(helloworld, [1, 5, 7])

关于python - 如何使用 Python 3 的多处理池运行 2 个不同的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46654626/

相关文章:

objective-c - Cocoa/Objective-C 中的后台(异步)编程

python - 将numpy数组逐行保存到txt文件

python - 当我在开始时得到几行新行时,如何从字母表开始打印

python - 使用 iterrows 对最后一次迭代值执行操作

python - 运行时警告: invalid value encountered in power while plotting poisson distribution

Python:WAITING文件以 CPU 友好的方式达到大小限制

C# 线程同步

javascript - JQuery 等待多个延迟解析

ios - 查找 Metal 纹理中的最小值和最大值

node.js - 异步等待然后在同一个函数上