简体   繁体   English

无法在 go 例程中获取多个通道值

[英]Cannot get the multiple channel values in go routines

I have written 2 goroutines for web socket read and write the message.我已经为 web socket 读写消息编写了 2 个 goroutine。 For Example,例如,

ch := make(chan bool)
folderName := make(chan string)

go func(co *websocket.Conn) {
    m, d, err := co.ReadMessage()
    fmt.Println(m, string(d), err)

    folderName <- string(d)
    ch <- true

    if string(d) == "closed" {
        ch <- true
        co.Close()
    }
}(conn)

This goroutine is used to read the message from the socket and update the channels.该 goroutine 用于从套接字读取消息并更新通道。

go func(co *websocket.Conn) {
    value := <-ch
    fldr := <-folderName

    fmt.Println(fldr, value)
}(conn)

This goroutine is for writing the message.该 goroutine 用于编写消息。 But I couldn't get folderName and ch channel values.但我无法获得 folderName 和 ch 通道值。 I don't know how to find the issues.不知道怎么找问题。

If I pass the single channel, I can get a message from the channel.如果我通过单个通道,我可以从通道中获取消息。 But I need to get 2 values in that goroutine.但是我需要在那个 goroutine 中获得 2 个值。

Could anyone help to resolve the issues?任何人都可以帮助解决这些问题吗? Thanks in advance.提前致谢。

In your case since your reading a single message from the websocket.Connection you need to change the sequence in which you read from the channels since your channels are unbuffered your writes will be blocked as longs as there are no consumers and vice versa.在您的情况下,因为您从websocket.Connection读取单个消息,您需要更改从通道读取的顺序,因为您的通道没有缓冲,只要没有消费者,您的写入就会被阻止,反之亦然。 In your case, you write to the folderName channel in the first goroutine and then read from the other channel ch so both of your goroutines will be blocked.在您的情况下,您写入第一个 goroutine 中的folderName通道,然后从另一个通道ch读取,因此您的两个 goroutine 都将被阻止。

package main

import (
    "fmt"
    "time"
)

func main() {
    ch := make(chan bool)
    folderName := make(chan string)

    go func() {
        ch <- true
        folderName <- "Some text"

        .
                .
                .
    }()

    go func() {
        value := <-ch
        fldr := <-folderName

        fmt.Println(fldr, value)
    }()

    time.Sleep(time.Second)
}

Playground example游乐场示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM