gpt4 book ai didi

python-2.7 - deferToThread 与 Deferred()

转载 作者:行者123 更新时间:2023-12-05 00:26:39 24 4
gpt4 key购买 nike

我想了解以下 2 个代码片段会发生什么 -

片段#1

from twisted.internet import threads, defer, reactor

def proc1(a):
while True:
print "Proc----------1"

def proc2(a):
while True:
print "Proc----------2"

def proc3(a):
while True:
print "Proc----------3"

d1 = threads.deferToThread(proc1)
d2 = threads.deferToThread(proc2)
d3 = threads.deferToThread(proc3)

reactor.run()

我的理解是所有线程并行运行,输出是 => 混合所有 procs 的 stdout

狙击手#2
from twisted.internet import threads, defer, reactor

def proc1(a):
while True:
print "Proc----------1"

def proc2(a):
while True:
print "Proc----------2"

def proc3(a):
while True:
print "Proc----------3"



d1 = defer.Deferred()
d2 = defer.Deferred()
d3 = defer.Deferred()

d1.addCallback(proc1)
d2.addCallback(proc2)
d3.addCallback(proc3)

d1.callback('a')
d2.callback('a')
d3.callback('a')

reactor.run()

对于这个片段 - 每个延迟回调都被一个接一个地触发,就输出而言,只有 proc1 标准输出会无限期地倾泻。

如果我错了,请纠正我。所以基本上我想理解和确认的是延迟对象一个接一个触发,而 deferToThread 并行运行,如名称线程。

最佳答案

Please correct me if I am wrong folks. So basically what i want to understand and confirm is Deferred objects are triggered one after the other whereas the deferToThread are run parallely as by the name thread.



这不完全正确,但它有点接近。这是触发您的延迟的代码:
d1.callback('a')
d2.callback('a')
d3.callback('a')

你一个接一个地触发了它们。这没有什么特别的或神秘的。这就是 Python 的工作方式。

延迟与线程无关。它们不会自动使代码非阻塞或异步或多线程。它们只是保留一个函数列表(您使用 addCallback 方法添加到该列表中),然后调用该列表中的函数(当您使用 callback 方法时)。

关于python-2.7 - deferToThread 与 Deferred(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21884013/

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