在 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来替代。我不知道为什么 he/she 删除了答案,因为它实际上工作得很好。所以,这是我的代码:

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