繁体   English   中英

在 Python2.7 中应用异步

[英]Apply Async in Python2.7

我试图为以前在 Python3 中工作的多处理编写一个简单的代码。 目前,我想将我的代码从 Python3.6 迁移到 Python2.7。 在 Python3.6 中,它显示了预期的结果,但在 Python 2.7 中没有。 有人说我需要使用with mp.Pool() as pool ,但结果是一样的。 这是我的代码:

from __future__ import print_function
from multiprocessing import Pool

class Try():
    def print_this(self, test):
        print(test)

x = Try()
pool = Pool(1)
for i in range(10):
    pool.apply_async(x.print_this, args=(i,))
pool.close()
pool.join()

Python3 会显示这个

0
1
2
3
4
5
6
7
8
9

但不是在 Python2 中。 你有什么建议吗? 谢谢你。

之前看到一个回答说需要使用ThreadPool作为替代。 我不知道他/她为什么删除了答案,因为它实际上工作得很好。 所以,这是我的代码:

from __future__ import print_function
from multiprocessing.pool import ThreadPool
# from multiprocessing.pool import Pool

class Try():
    def print_this(self, test):
        print(test)

# x = Try()
# pool = Pool(1)
# for i in range(10):
#     pool.apply_async(x.print_this, args=(i,))
# pool.close()
# pool.join()

x = Try()
pool = ThreadPool(processes=1)
pool.map_async(x.print_this, [i for i in range(10)])
pool.close()
pool.join()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM