如果选择具有默认值,则不会发送到频道



我正在做一个个人项目,该项目将在带有一些传感器的Raspberry Pi上运行。

从传感器读取的函数和处理套接字连接的函数在不同的 goroutines 中执行,因此,为了在从传感器读取数据时在套接字上发送数据,我在 main 函数中创建了一个chan []byte并将其传递给 goroutines。

我的问题就在这里出现了:如果我连续进行多次写入,只有第一个数据到达客户端,而其他数据则不会。但是,如果我在发送函数中放一点time.Sleep,所有数据都会正确到达客户端。

无论如何,这是这个小程序的简化版本:

package main
import (
"net"
"os"
"sync"
"time"
)
const socketName string = "./test_socket"
// create to the socket and launch the accept client routine
func launchServerUDS(ch chan []byte) {
if err := os.RemoveAll(socketName); err != nil {
return
}
l, err := net.Listen("unix", socketName)
if err != nil {
return
}
go acceptConnectionRoutine(l, ch)
}
// accept incoming connection on the socket and
// 1) launch the routine to handle commands from the client
// 2) launch the routine to send data when the server reads from the sensors
func acceptConnectionRoutine(l net.Listener, ch chan []byte) {
defer l.Close()
for {
conn, err := l.Accept()
if err != nil {
return
}
go commandsHandlerRoutine(conn, ch)
go autoSendRoutine(conn, ch)
}
}
// routine that sends data to the client
func autoSendRoutine(c net.Conn, ch chan []byte) {
for {
data := <-ch
if string(data) == "exit" {
return
}
c.Write(data)
}
}
// handle client connection and calls functions to execute commands
func commandsHandlerRoutine(c net.Conn, ch chan []byte) {
for {
buf := make([]byte, 1024)
n, err := c.Read(buf)
if err != nil {
ch <- []byte("exit")
break
}
// now, for sake of simplicity , only echo commands back to the client
_, err = c.Write(buf[:n])
if err != nil {
ch <- []byte("exit")
break
}
}
}
// write on the channel to the autosend routine so the data are written on the socket
func sendDataToClient(data []byte, ch chan []byte) {
select {
case ch <- data:
// if i put a little sleep here, no problems
// i i remove the sleep, only data1 is sent to the client
// time.Sleep(1 * time.Millisecond)
default:
}
}
func dummyReadDataRoutine(ch chan []byte) {
for {
// read data from the sensors every 5 seconds
time.Sleep(5 * time.Second)
// read first data and send it
sendDataToClient([]byte("dummy data1n"), ch)
// read second data and send it
sendDataToClient([]byte("dummy data2n"), ch)
// read third data and send it
sendDataToClient([]byte("dummy data3n"), ch)
}
}
func main() {
ch := make(chan []byte)
wg := sync.WaitGroup{}
wg.Add(2)
go dummyReadDataRoutine(ch)
go launchServerUDS(ch)
wg.Wait()
}

我认为使用睡眠来同步写入是不正确的。我如何解决此问题,同时保持函数在不同的不同 goroutines 上运行。

主要问题在于函数:

func sendDataToClient(data []byte, ch chan []byte) {
select {
case ch <- data:
// if I put a little sleep here, no problems
// if I remove the sleep, only data1 is sent to the client
// time.Sleep(1 * time.Millisecond)
default:
}

如果在调用函数时通道ch尚未准备就绪,则将采用default情况,并且永远不会发送data。在这种情况下,您应该取消该功能并直接发送到通道。

缓冲通道与手头的问题正交,并且应该出于与缓冲 IO 类似的原因进行,即为无法立即进行的写入提供"缓冲区"。如果代码在没有缓冲区的情况下无法进行,则添加一个缓冲区只会延迟可能的死锁。

您在这里也不需要exit哨兵值,因为您可以在通道上划清范围并在完成后关闭它。然而,这仍然忽略了写入错误,但这同样需要重新设计。

for data := range ch {
c.Write(data)
}

您还应该小心通过通道传递切片,因为很容易忘记哪个逻辑进程具有所有权并将修改后备阵列。我不能从给出的信息中说通过通道传递读+写数据是否会改善架构,但这不是您在大多数 go 网络代码中可以找到的模式。

JimB给出了很好的解释,所以我认为他的答案更好。

我在这个答案中包含了我的部分解决方案。

我以为我的代码是清晰和简化的,但正如 Jim 所说,我可以做得更简单、更清晰。我把我的旧代码张贴出来,这样人们就可以更好地理解如何发布更简单的代码,而不是像我一样一团糟。

正如 chmike 所说,我的问题并不像我想的那样与插座有关,而只与频道有关。在无缓冲通道上写入是问题之一。将无缓冲通道更改为缓冲通道后,问题已解决。无论如何,这段代码不是"好代码",可以按照 JimB 在他的答案中写的原则进行改进。

所以这是新代码:

package main
import (
"net"
"os"
"sync"
"time"
)
const socketName string = "./test_socket"
// create the socket and accept clients connections
func launchServerUDS(ch chan []byte, wg *sync.WaitGroup) {
defer wg.Done()
if err := os.RemoveAll(socketName); err != nil {
return
}
l, err := net.Listen("unix", socketName)
if err != nil {
return
}
defer l.Close()
for {
conn, err := l.Accept()
if err != nil {
return
}
// this goroutine are launched when a client is connected
// routine that listen and echo commands
go commandsHandlerRoutine(conn, ch)
// routine to send data read from the sensors to the client
go autoSendRoutine(conn, ch)
}
}
// routine that sends data to the client
func autoSendRoutine(c net.Conn, ch chan []byte) {
for {
data := <-ch
if string(data) == "exit" {
return
}
c.Write(data)
}
}
// handle commands received from the client
func commandsHandlerRoutine(c net.Conn, ch chan []byte) {
for {
buf := make([]byte, 1024)
n, err := c.Read(buf)
if err != nil {
// if i can't read send an exit command to autoSendRoutine and exit
ch <- []byte("exit")
break
}
// now, for sake of simplicity , only echo commands back to the client
_, err = c.Write(buf[:n])
if err != nil {
// if i can't write back send an exit command to autoSendRoutine and exit
ch <- []byte("exit")
break
}
}
}
// this goroutine reads from the sensors and write to the channel , so data are sent
// to the client if a client is connected
func dummyReadDataRoutine(ch chan []byte, wg *sync.WaitGroup) {
x := 0
for x < 100 {
// read data from the sensors every 5 seconds
time.Sleep(1 * time.Second)
// read first data and send it
ch <- []byte("data1n")
// read second data and send it
ch <- []byte("data2n")
// read third data and send it
ch <- []byte("data3n")
x++
}
wg.Done()
}

func main() {
// create a BUFFERED CHANNEL
ch := make(chan []byte, 1)
wg := sync.WaitGroup{}
wg.Add(2)
// launch the goruotines that handle the socket connections
// and read data from the sensors
go dummyReadDataRoutine(ch, &wg)
go launchServerUDS(ch, &wg)
wg.Wait()
}

最新更新