2

I had a Python 2 script that creates a bunch Thread objects into a list:

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

Directly below that I started all of them:

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

which should just call start() on all members of that list.

My thread class has __init__ overridden and some output in 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())
    ...

All works fine in Python 2.

Then I migrated the module to Python 3 and... I never saw the message My thread run()... anymore. Strange.

But when I change the code for calling start() to:

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

everything was back to normal.

It seems to me that the semantics for the call of

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

must have changed. Is that the case? Has it been optimized out because I do not assign the result anywhere? Or am I overlooking somehting else?

towi
  • 21,587
  • 28
  • 106
  • 187
  • 1
    Style tip: map and list comprehensions are usually employed when you want to do something with the resulting list/generator. Otherwise, it may make more sense to use a regular for loop: `for t in myWorkers: t.start()`. This is actually fewer characters than `map(lambda t: t.start(), myWorkers)`. – Kevin Sep 06 '19 at 13:55

0 Answers0