发送数据通过通道时卡住了。

huangapple go评论69阅读模式
英文:

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 (
	&quot;log&quot;
	&quot;time&quot;
)

var resp chan string

func main() {
	go send()
	listen()
}

func listen() {
	select {
	case response := &lt;-resp:
		log.Printf(&quot;Writing response: %s\n&quot;, response)
	}
}

func send() {
	ticker := time.NewTicker(time.Duration(10000) * time.Millisecond)

	select {
	case &lt;-ticker.C:
		// program gets stuck here
		log.Println(&quot;Sending&quot;)
		resp &lt;- &quot;Message&quot;
	}
}

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)

huangapple
  • 本文由 发表于 2015年5月23日 13:09:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/30409099.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定