首页 > 解决方案 > 对于优化表达式,python 2 和 python 3 之间的语义是否存在差异?

问题描述

我有一个 Python 2 脚本,可以将一堆Thread对象创建到一个列表中:

myWorkers = [ MyThread(num)  for num in range(5) ]

就在下面,我开始了所有这些:

map(lambda t: t.start(), myWorkers)

它应该只调用start()该列表的所有成员。

我的线程类已__init__被覆盖,一些输出在run()

class MyThread(Thread):
  def __init__(self, num):
    super(MyThread, self).__init__(name="Thread-%s" % num)
    self.num = num
  def run(self):
    logger.debug("My thread run() %s" % self.getName())
    ...

在 Python 2 中一切正常。

然后我将该模块迁移到 Python 3 并且......我再也没有看到该消息My thread run()...。奇怪的。

但是当我将调用代码更改为start()

for i, t in enumerate(myWorkers):
    logger.debug("starting my-worker %d..." % i)
    t.start()
    time.sleep(0.1)

一切恢复正常。

在我看来,调用的语义

map(lambda t: t.start(), myWorkers)

一定是变了。是这样吗?它是否因为我没有在任何地方分配结果而被优化?还是我忽略了其他东西?

标签: pythonpython-3.xpython-multithreading

解决方案


推荐阅读