使用 futures 遇到的疑惑

2016-07-05 01:27:32 +08:00
 imcocc

示例代码 python 2.7

# -*- coding: utf-8 -*-
from concurrent import futures

def test(i):
   print i


def mu():
   list=["a","b","c","d"]

   with futures.ThreadPoolExecutor(max_workers=2) as executor:

       future_tasks=dict((executor.submit(test, i), i)
                        for i in list)
       for future in futures.as_completed(future_tasks):
           print future.result()
if __name__ == '__main__':

   mu()

打印结果

a
b
c
d
None
None
None
None

在学 python.照着官方文档写的, 疑惑的是 开 2 个 works, 第一个线程把 list 都打印了,第二个线程返回 none.

不知道是哪里出错了 ? 请知道的朋友说一下。谢谢啦

2779 次点击
所在节点    Python
5 条回复
justou
2016-07-05 02:03:32 +08:00
None 是两个线程中 test 的返回值, 两个线程都在抢着打印.
py3 的 print 不是函数调用不报错?
quxw
2016-07-05 09:57:21 +08:00
a,b,c,d 是 test 里的 print

test 又没有返回值,当然是 None 了
mongost3t
2016-07-05 10:00:48 +08:00
你 test 没返回数据, result()就是 None 了
mongost3t
2016-07-05 10:01:12 +08:00
咦楼上上……
imcocc
2016-07-05 10:53:07 +08:00
@justou 这个是 python 2.7

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/290287

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX