【问题标题】:print() inside thread outputs wrong value [duplicate]线程内的print()输出错误的值[重复]
【发布时间】:2021-05-30 07:16:59
【问题描述】:

我正在尝试重新创建一个称为睡眠排序的愚蠢想法,但是输出与预期相去甚远。

我期待

0
1
2
3
5

但是我得到了

0
5
5
5
5

...这很奇怪,因为线程会:休眠 (item) 秒,然后打印该项目。

这是我的代码

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

我的代码有问题吗?非常感谢您!

【问题讨论】:

  • 我不太清楚你的方法中排序逻辑发生在哪里。
  • @anddt 列表中的每个项目都有自己的线程,它会在其中休眠 (item) 秒。最大的数字休眠时间最长,最后打印,最小的数字最先打印。

标签: python multithreading sorting


【解决方案1】:

这是许多语言的典型行为,由“后期绑定”引起。你应该明确地传递参数以避免这种情况,也应该谷歌诸如“python后期绑定”之类的东西。

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

【讨论】:

  • 这也有效!几秒钟前,我发现可能是因为在 time.sleep(item) 之后,for 循环中 (item) 的值是什么,都会被打印出来。我在线程内添加了“temp = item”,它也可以工作。谢谢,我第一次听说延迟绑定,觉得这可能是原因并且有人确认了这一点,感觉很棒。
  • 您能否解释一下为什么先出现0,然后出现5?如果是后期绑定,那么为什么不是全部0 或全部5
  • @python_user 我想因为sleep(0),这个线程有时间使用它启动时相同的item值来执行。
  • 有道理,谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多