【问题标题】:Python - Run multi functions with 1 threadPython - 使用 1 个线程运行多功能
【发布时间】:2020-09-25 15:07:15
【问题描述】:

我是 Python 新手。我正在尝试做某事,但不确定是否可行。 我想创建一个运行 1 个函数的线程,然后运行另一个函数。

例如

thread.start_new_thread( func1 )
//Run this thread only after the first one was finished
thread.start_new_thread( func2 )

可以用 1 个线程来完成吗?或者我需要创建 2 个线程? 我该怎么办?

【问题讨论】:

  • 您的意思是:def func3(): func1();func2()
  • 我的意思是创建一个线程实例。使用这个实例运行两个函数,一个接一个。

标签: python multithreading thread-safety threadpool


【解决方案1】:

如果您希望相同的线程同时运行这两个函数,您可以使用 func3 启动线程,该线程调用 func1,然后调用 func2。

def func3:
    func1()
    func2()

thread.start_new_thread(func3, ())

另一方面,您可以使用“线程”库并启动一个运行 func1 的线程,等到它完成后再启动一个运行 func2 的线程:

import threading
t = threading.Thread(target = func1)
t.start()
t.join() # Waits until it is finished
t = threading.Thread(target = func2)
t.start()

【讨论】:

    猜你喜欢
    • 2015-07-10
    • 1970-01-01
    • 2014-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多