这个 goroutine 阻塞...
go log.Fatal(http.ListenAndServe(":8000", nil))
log.Print("This doesn't print")
Run Code Online (Sandbox Code Playgroud)
这个 goroutine 不会阻塞...
go func() {
log.Fatal(http.ListenAndServe(":8000", nil))
}()
log.Print("This prints")
Run Code Online (Sandbox Code Playgroud)
这个 goroutine 也不会阻塞...
go http.ListenAndServe(":8000", nil)
log.Print("This prints")
Run Code Online (Sandbox Code Playgroud) 我有一个问题。这是示例:https: //play.golang.org/p/QSWY2INQuSE
func Avg(c chan string, wg *sync.WaitGroup) {
defer wg.Done()
c <- "test"
}
func main() {
var wg sync.WaitGroup
c := make(chan string)
timer1 := time.NewTicker(5 * time.Second)
for {
select {
case <-timer1.C:
wg.Add(1)
go Avg(c, &wg)
wg.Wait()
}
}
fmt.Println(<-c)
}
Run Code Online (Sandbox Code Playgroud)
为什么数据达不到fmt.Println(<-c)
谢谢你!
我有一个 go 程序,它使用 goroutine 来读取 UDP 数据包。我想使用 select 子句和“停止”通道来关闭 goroutine,以便在不再需要时立即关闭。
这是 goroutine 的简单代码示例:
func Run(c chan string, q chan bool, conn *net.UDPConn) {
defer close(c)
buf := make([]byte, 1024)
for {
select {
case <- q:
return
default:
n, _, err := conn.ReadFromUDP(buf)
c <- string(buf[0:n])
fmt.Println("Received ", string(buf[0:n]))
if err != nil {
fmt.Println("Error: ", err)
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
连接创建为:
conn, err := net.ListenUDP("udp",addr.Addr)
Run Code Online (Sandbox Code Playgroud)
Goroutine 应该使用以下命令终止:
close(q)
Run Code Online (Sandbox Code Playgroud)
关闭“停止”通道(“q”)后,goroutine 不会立即停止。我需要通过 UDP 连接再发送一个字符串。当这样做时,goroutine 就会停止。我根本不理解这种行为,如果有人能启发我,我将不胜感激。
先感谢您!
有问题清单。我一一向用户展示问题并等待用户的回答。每个问题都应该在几秒钟内得到回答(例如问题 5 秒)。如果问题得到正确且及时的回答,那么用户将获得一些积分。我的代码看起来像:
for i := 0; i < len(questions); i++ {
fmt.Println(questions[i].Text)
ans := make(chan int)
go func() {
fmt.Print("Enter answer ")
var u int
fmt.Scanf("%d\n", &u)
ans <- u
}()
select {
case userAnswer := <-ans:
if userAnswer == questions[i].Answer {
points++
}
case <-time.After(5 * time.Second):
fmt.Println("\n Time is over!")
}
}
Run Code Online (Sandbox Code Playgroud)
接下来的问题是:如果用户不回答问题,那么他会收到消息“时间结束”,如预期的那样。但下一个答案将不会被处理,用户应该再次输入。它看起来像下一个输出:
question with answer 1
Enter answer: 1
1 is right answer
question with answer 2
Enter answer: 2
2 is right answer
question with …Run Code Online (Sandbox Code Playgroud) 我们可以使用如下语句发送响应(或在用户端写入):
json.NewEncoder(w).Encode("some data")
Run Code Online (Sandbox Code Playgroud)
在执行一些计算部分之前,在 api 中,这些计算部分不需要响应,但需要存储在数据库中。我想我们可以在更短的时间内向用户提供响应,并且函数的其他部分将继续工作直到返回语句。
如果我的思考方向错误,请纠正我。
我有一些这样的代码:
go func(ch chan bool) chan bool {
// some processing
ch <- true
return ch
}(ch)
for i := 0; i < TotalQuestions; i++ {
// check if channel ch has some value
// If it has then execute below statements, else break out of the loop
fmt.Println(questions[i])
answer, _ := InputReader.ReadString('\n')
// some processing
}
fmt.Println("Your Total score is " + strconv.Itoa(TotalScore) + " out of " + strconv.Itoa(TotalQuestions))
Run Code Online (Sandbox Code Playgroud)
现在我想做的是检查通道 ch 是否有值(在 for 循环中)。如果它有一个值,那么我想跳出 for 循环来打印最后一条语句。否则,我想继续我的循环。我尝试插入选择块,但这不起作用(通道被阻止并且代码没有打印问题)。怎么做?
我有一个应用程序。它创建一个 HTTP 服务来监听一些连接点,我们可以用它来检查应用程序状态。
该服务在后台运行(带有 go 例程)。
它在函数中被初始化,init()其中包括:
func init() {
...
initHttpEndPoints();
...
}
Run Code Online (Sandbox Code Playgroud)
在测试此应用程序时,在函数中创建 go 例程是否会init()导致问题?
我问这个问题是因为看起来我的测试重新运行了init()第二次,我想知道为什么会这样以及副作用可能是什么......(如果所有的 go 例程突然都发生的话,可能不太好重复。)
注意:完整的应用程序。在函数中创建数百个 go 例程init()。我使用 HTTP 端点作为示例。
强烈相关的答案:测试是否同时运行?
// By default channels are _unbuffered_, meaning that they
// will only accept sends (`chan <-`) if there is a
// corresponding receive (`<- chan`) ready to receive the
// sent value. _Buffered channels_ accept a limited
// number of values without a corresponding receiver for
// those values.
package main
import "fmt"
func main() {
// Here we `make` a channel of strings buffering up to
// 2 values.
messages := make(chan string, 2)
// Because this channel is …Run Code Online (Sandbox Code Playgroud) package main
import (
"fmt"
"sync"
)
func main(){
ch1 := make(chan int,100)
ct := 0
var wg sync.WaitGroup
wg.Add(1)
go func(){
//defer close(ch1)
for i:= 0; i < 10;i ++{
ch1 <- i
}
}()
go func(){
defer wg.Done()
for x := range ch1{
fmt.Println(x)
}
}()
wg.Wait()
fmt.Println("numbers:",ct)
}
Run Code Online (Sandbox Code Playgroud)
为什么这个代码会返回
fatal error: all goroutines are asleep - deadlock!
我发现如果我关闭通道不会有死锁,但我不知道为什么会这样。将所有项目输入频道后是否必须关闭频道?
如果是,如何确定该最大值?这对我来说是最重要的部分。我真的很想手动设置它。我考虑使用runtime.GOMAXPROCS(0),因为我怀疑更多的并行性会产生任何额外的好处。该评论似乎表明,它在某个时候被标记为弃用。
据我所知,Go 例程的唯一限制因素是内存,因为休眠的 Go 例程仍然需要内存来存储其堆栈。
go ×10
goroutine ×10
channel ×4
concurrency ×4
http ×1
nonblocking ×1
response ×1
udp ×1
unit-testing ×1