我的情况:
time.Ticker
读取一条消息。因此,问题是:生产者如何才能尽可能晚地生成一条消息?
显示总体思路的示例代码:
func producer() {
for {
select {
...
case pipe <- generateMsg():
// I'd like to call generateMsg as late as possible,
// i.e. calculate the timestamp when I know
// that writing to the channel will not block.
}
}
}
func consumer() {
for {
select {
...
case <-timeTicker.C:
// Reading from the consumer.
msg <- pipe
...
}
}
}
完整的代码(与上面略有不同)可以在Go Playground获得:https://play.golang.org/p/y0oCf39AV6P
我的一个主意是检查写入通道是否会阻塞。如果它不会阻止,那么我可以生成一条消息然后发送。但是...
另一个(坏的)想法:
func producer() {
var msg Message
for {
// This is BAD. DON'T DO THIS!
select {
case pipe <- msg:
// It may send the same message multiple times.
default:
msg = generateMsg()
// It causes a busy-wait loop, high CPU usage
// because it re-generates the message all the time.
}
}
}
答案 0 :(得分:0)
This answer(针对Go non-blocking channel send, test-for-failure before attempting to send?)建议使用第二个通道将信号从消费者发送到生产者:
timer.Ticker
的滴答声之后)。