【问题标题】:Python time.sleep lock processPython time.sleep 锁进程
【发布时间】:2015-05-25 12:48:42
【问题描述】:

我想创建多进程应用程序。这是示例:

import threading
import time
from logs import LOG


def start_first():
    LOG.log("First thread has started")
    time.sleep(1000)


def start_second():
    LOG.log("second thread has started")


if __name__ == '__main__':
    ### call birhtday daemon
    first_thread = threading.Thread(target=start_first())

    ### call billing daemon
    second_thread = threading.Thread(target=start_second())

    ### starting all daemons
    first_thread.start()
    second_thread.start()

在此代码中,第二个线程不起作用。我猜,在first_thread 内调用睡眠函数后,主进程被睡眠了。我找到了this post。但是这里 sleep 是与 class 一起使用的。我明白了(进程以退出代码 0 结束 ) 结果,当我运行答案时。谁能解释我在哪里犯了错误?

  • 我在 windows 上使用 python 3.*

【问题讨论】:

  • 它实际上会运行,但是您在方法 1 中的 time.sleep(1000) 太长了,您必须等待 1000 秒,将其更改为 time.sleep(5) 以查看即时结果。
  • 好的,但是它阻塞了第二个线程。为什么会这样?

标签: python multithreading thread-sleep


【解决方案1】:

创建线程时,您实际上是在尝试为Thread 设置目标而不是向其传递函数时调用函数。这意味着当您尝试创建first_thread 时,您实际上是在调用start_first,其中包括很长的睡眠时间。我想你会因为没有看到第二个线程的输出而感到沮丧并杀死它,对吧?

从你的 target= 语句中删除括号,你会得到你想要的

first_thread = threading.Thread(target=start_first)
second_thread = threading.Thread(target=start_second)
first_thread.start()
second_thread.start()

会做你想做的事

【讨论】:

  • 另外,如果你想为带参数的函数创建线程,你可以使用first_thread = threading.Thread(target=start_first, args = ())
猜你喜欢
  • 2020-07-23
  • 2021-11-13
  • 2010-09-10
  • 1970-01-01
  • 2021-08-04
  • 1970-01-01
  • 2015-05-18
  • 1970-01-01
  • 2012-03-03
相关资源
最近更新 更多