Go具有在通道上起作用的select语句。从文档中:
select语句使goroutine等待多个通信操作。
select会阻塞,直到其中一种情况可以运行,然后再执行该情况。如果准备好多个,它将随机选择一个。
是否存在与以下代码等效的Python:
package main
import "fmt"
func main() {
c1 := make(chan int)
c2 := make(chan int)
quit := make(chan int)
go func() {
for i := 0; i < 10; i++ {
c1 <- i
}
quit <- 0
}()
go func() {
for i := 0; i < 2; i++ {
c2 <- i
}
}()
for {
select {
case <-c1:
fmt.Println("Received value from c1")
case <-c2:
fmt.Println("Received value from c2")
case <-quit:
fmt.Println("quit")
return
}
}
}
该程序的输出:
Received value from c1
Received value from c1
Received value from c2
Received value from c1
Received value from c2
Received value from c1
Received value from c1
Received value from c1
Received value from c1
Received value from c1
Received value from c1
Received value from c1
quit
这是一个非常直接的翻译,但是“选择多个是否准备就绪”部分的工作方式有所不同-只是采用了第一个。这也就像使用运行代码gomaxprocs(1)
。
import threading
import Queue
def main():
c1 = Queue.Queue(maxsize=0)
c2 = Queue.Queue(maxsize=0)
quit = Queue.Queue(maxsize=0)
def func1():
for i in range(10):
c1.put(i)
quit.put(0)
threading.Thread(target=func1).start()
def func2():
for i in range(2):
c2.put(i)
threading.Thread(target=func2).start()
combined = Queue.Queue(maxsize=0)
def listen_and_forward(queue):
while True:
combined.put((queue, queue.get()))
t = threading.Thread(target=listen_and_forward, args=(c1,))
t.daemon = True
t.start()
t = threading.Thread(target=listen_and_forward, args=(c2,))
t.daemon = True
t.start()
t = threading.Thread(target=listen_and_forward, args=(quit,))
t.daemon = True
t.start()
while True:
which, message = combined.get()
if which is c1:
print 'Received value from c1'
elif which is c2:
print 'Received value from c2'
elif which is quit:
print 'Received value from quit'
return
main()
基本更改是使用组合消息的线程来模拟选择。如果要大量使用此模式,则可以编写一些选择代码:
import threading
import Queue
def select(*queues):
combined = Queue.Queue(maxsize=0)
def listen_and_forward(queue):
while True:
combined.put((queue, queue.get()))
for queue in queues:
t = threading.Thread(target=listen_and_forward, args=(queue,))
t.daemon = True
t.start()
while True:
yield combined.get()
def main():
c1 = Queue.Queue(maxsize=0)
c2 = Queue.Queue(maxsize=0)
quit = Queue.Queue(maxsize=0)
def func1():
for i in range(10):
c1.put(i)
quit.put(0)
threading.Thread(target=func1).start()
def func2():
for i in range(2):
c2.put(i)
threading.Thread(target=func2).start()
for which, msg in select(c1, c2, quit):
if which is c1:
print 'Received value from c1'
elif which is c2:
print 'Received value from c2'
elif which is quit:
print 'Received value from quit'
return
main()
请注意,尽管您的程序无关紧要,但该选择并不是一个可行的选择-goroutine可能会在一个通道中发送结果,该通道将在选择中排队,如果我们不总是对它进行迭代,则会丢失该结果。选择完成!
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句