go - Go 中的缓冲 channel

标签 go concurrency channels

我正在使用 raspberry pi 和 arduino 开发一个项目。我正在树莓派上编写一个 GO 程序,以每秒 115200 的波特率从 Arduino 接收 UART 数据。树莓派读取 UART 数据,将其保存到文件中(根据 file1file2 等的值),然后将文件发送到 ftp 服务器。

由于上传到服务器可能需要一些时间,具体取决于网络,我想使用 go 并发,这样 UART 读取和保存到文件就不会中断。以下是我尝试应用的伪代码(骨架)。我在代码中的想法是文件路径将按顺序缓冲在 channel 中,并以相同的顺序执行上传。我做得对吗?有没有更好的方法来解决这个问题?

package main

import "strings"

func SendFile(filePath string) {

}
// based on the value of the data, SaveToFile saves the data to either file1, file2 or file3
func SaveToFile(uartData []string) filePath string {

    return filePath
}

func main() {


    ch := make(chan string, 1000)

    //uartInit initialization goes here
    uart := uartInit()

    //infinite loop for reading UART...
    for {
        buf := 1024 // UART buffer
        data := uart.Read(buf)
        uartData = strings.Split(string(buf), " ")

        //channel receives filepath 
        ch <- SaveToFile(uartData)

        //channel sends filepath
        go SendFile(<-ch)

    }
}

最佳答案

您正在向 channel 写入一个字符串,然后将其读回。 sendFile() 在不同的 goroutine 中运行,但在您使用它的方式中不需要 channel 。你可以简单地做

 fname:= SaveToFile(uartData)
 go SendFile(fname)

但是,我不认为这是你想要做的。

相反,您应该有一个 goroutine,您可以在其中从 UART 读取数据,并写入缓冲 channel 。监听该 channel 的是另一个将数据 block 写入文件的 goroutine。准备好发送时,创建第三个 goroutine 来发送文件。

关于go - Go 中的缓冲 channel ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57488619/

相关文章:

java - 快速切换位顺序的方法?

c++ - 是什么保证弱松弛的无竞争 CAS 循环终止?

java - AtomicReference<Integer> 与 AtomicInteger 之间有什么区别?

Django Channels 从 Celery 任务发送组消息。异步事件循环在所有异步任务完成之前停止

go - 测试在 Go 中使用 fmt.Scanf() 的函数

go - 设置与 govendor 的依赖关系的具体提交

performance - 迄今为止的 CSV 和 float

mysql - 从 MySQL 检索唯一标识符

python - 在 Python 中分别编辑左右音轨 channel

amazon-web-services - 使用 Goroutines 和 Channels 将多个文件并行上传到 Amazon S3