gpt4 book ai didi

python - 用于管理线程的替代 python 库

转载 作者:行者123 更新时间:2023-11-28 19:57:54 26 4
gpt4 key购买 nike

我对产生子进程有一些烦恼,比如获得正确的输出等等。包装库,envoy ,通过易于使用的界面解决了我的所有问题,消除了大多数问题。

使用线程时,我有时会遇到无法结束的挂起进程、在我无法再访问的线程中启动的外部程序等问题。

那里有任何“傻瓜线程”python 库吗?谢谢

最佳答案

那里有任何“傻瓜线程”python 库吗?

不,没有。 threading在简单的情况下使用起来非常简单。你想用它在你的程序中引入并发。这意味着只要您希望两个或多个操作同时发生,即同时发生,您就可以使用它。

这样你就可以让彼得盖房子,同时让伊戈尔开车去莫斯科:

from threading import Thread
import time

def drive_bus():
time.sleep(1)
print "Igor: I'm Igor and I'm driving to... Moskow!"
time.sleep(9)
print "Igor: Yei, Moskow!"

def build_house():
print "Peter: Let's start building a large house..."
time.sleep(10.1)
print "Peter: Urks, we have no tools :-("

threads = [Thread(target=drive_bus), Thread(target=build_house)]

for t in threads:
t.start()

for t in threads:
t.join()

是不是很简单?定义要在另一个线程中运行的函数。创建一个 threading.Thread 实例,并将该函数作为 target。到目前为止什么都没有发生,直到您调用 start。它触发线程并立即返回

在让您的主线程退出之前,您应该等待您生成的所有线程完成。这就是 t.join() 所做的:它阻塞并等待线程 t 完成。只有这样它才会返回。

关于python - 用于管理线程的替代 python 库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12586943/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com