Search code examples
pythonmultithreadinglate-binding

print() inside thread outputs wrong value


I'm trying to recreate a stupid idea called sleep sort, however the output is far from expected.

I am expecting

0
1
2
3
5

However I get

0
5
5
5
5

...which is wierd because the thread does: sleep for (item) seconds and then print that item.

Here's my code

import threading
import time

def sleepSort(lst):
    for item in lst:
        threading.Thread(target = lambda: (
            time.sleep(item),
            print(item)
        )).start()

sleepSort([3, 0, 2, 1, 5])

Is there something wrong with my code? Thank you very much in advance!


Solution

  • It's typical behavior for many languages and caused by "late binding". You should pass argument explicitly to avoid this and also google something like "python late binding".

    def sleepSort(lst):
        for item in lst:
            threading.Thread(target = lambda item: (
                time.sleep(item),
                print(item)
            ), args=(item, )).start()