英文:
Sending data through channel gets stuck
问题
我正在写一个使用长轮询的服务器,基本上我有一个定期运行的Go协程,通过通道发送响应。然而,当它尝试发送到通道时,程序会卡住。
我制作了一个简单的程序来演示这个问题:
package main
import (
"log"
"time"
)
var resp chan string
func main() {
go send()
listen()
}
func listen() {
select {
case response := <-resp:
log.Printf("Writing response: %s\n", response)
}
}
func send() {
ticker := time.NewTicker(time.Duration(10000) * time.Millisecond)
select {
case <-ticker.C:
// 程序在这里卡住
log.Println("Sending")
resp <- "Message"
}
}
有人看到问题可能是什么吗?谢谢。
英文:
I'm writing a server that uses long polling, and basically I have a go routine that runs periodically and sends a response over a channel. However the program gets stuck when it tries to send into the channel.
I've made a simple program that demonstrates the problem:
package main
import (
"log"
"time"
)
var resp chan string
func main() {
go send()
listen()
}
func listen() {
select {
case response := <-resp:
log.Printf("Writing response: %s\n", response)
}
}
func send() {
ticker := time.NewTicker(time.Duration(10000) * time.Millisecond)
select {
case <-ticker.C:
// program gets stuck here
log.Println("Sending")
resp <- "Message"
}
}
Does anyone see what the problem could be? Thanks
答案1
得分: 5
在使用之前,你需要先创建一个通道。
var resp = make(chan string)
请注意,这是一个示例代码片段,用于在Go语言中创建一个字符串类型的通道。
英文:
You have to make a channel first before using it
var resp = make(chan string)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论