gpt4 book ai didi

python - 从示例代码中理解goless.select

转载 作者:IT王子 更新时间:2023-10-29 02:23:53 26 4
gpt4 key购买 nike

我发现了 Goroutines 的 python 实现,https://goless.readthedocs.org/en/latest/和玩耍

给出文档中的以下代码:

c1 = goless.chan()
c2 = goless.chan()

def func1():
time.sleep(1)
c1.send('one')
goless.go(func1)

def func2():
time.sleep(2)
c2.send('two')
goless.go(func2)

for i in range(2):
case, val = goless.select([goless.rcase(c1), goless.rcase(c2)])
print(val)

它打印:

one
two

关于select方法的文档

Select the first case that becomes ready. If a default case (goless.dcase) is present, return that if no other cases are ready. If there is no default case and no case is ready, block until one becomes ready.

所以我继续将 sleep(1) 更改为 sleep(3) 如下:

c1 = goless.chan()
c2 = goless.chan()

def func1():
time.sleep(3)
c1.send('one')
goless.go(func1)

def func2():
time.sleep(2)
c2.send('two')
goless.go(func2)

for i in range(2):
case, val = goless.select([goless.rcase(c1), goless.rcase(c2)])
print(val)

我认为它会打印:

two
one

但是它打印了:

one
two

这是为什么?

最佳答案

因为没有答案所以我去挖项目仓库,在这里发现了一个类似的问题:

https://github.com/rgalanakis/goless/issues/42

最值得注意的:

using time.sleep just pauses the current thread. It does not do any switching between coroutines. You would have to use gevent.sleep or a similar mechanism for Stackless (or goless.backend.yield).

看来我误解了 goless 会创建不同的线程,但我错了。

关于python - 从示例代码中理解goless.select,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31467321/

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