首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我是否正确地使用Golang并发来提高可靠性?

我是否正确地使用Golang并发来提高可靠性?
EN

Code Review用户
提问于 2013-02-23 01:26:57
回答 1查看 1.4K关注 0票数 3

这段代码从标准输入中获取文本,将其映射到结构(如果可能的话),并由此创建一个JSON字符串。

我使用条形码扫描器作为输入,我尝试使用goroutines来确保如果解析或JSON编组出现问题,程序将继续接收和处理来自扫描仪的输入。

我做得对吗?我是以最有效、最有效率、最惯用的方式做的吗?

因为我只关心这个帖子的并发性,所以我忽略了所有解析输入和创建JSON的代码。另外,我现在对JSON所做的唯一事情就是把它打印出来。

谢谢你看这个。

代码语言:javascript
复制
package main

import (
    "fmt"
    "status2/shoporder"
)

func main() {
    var input string
    for input != "exit" {
        fmt.Scanln(&input)
        ch := make(chan string)
        quit := make(chan bool)
        go parseInput(input, ch, quit)
        go sendJson(ch, quit)
    }
}

// Take the input and generate some JSON, then return it along a channel.
func parseInput(input string, ch chan string, quit chan bool) {
    // shoporder.Parse() uses regexp to validate the input, and returns a JSON string.
    son, ok := shoporder.Parse(input)
    if !ok {
        // If the input could not be parsed into JSON, then ignore and shut down
        // both goroutines.
        quit <- true
        return
    }
    ch <- son
}

// This will eventually send the JSON using websockets, but for now I just
// print it back out.
func sendJson(ch chan string, quit chan bool) {
    select {
    case json := <-ch:
        // For now I just print the JSON.
        fmt.Println(json)
    case <-quit:
        // I make sure to quit the goroutine, because I'm worried about creating a 
        // bunch that never end and just hang around.  Do I need to do this?
        return
    }
}
EN

回答 1

Code Review用户

回答已采纳

发布于 2013-02-25 18:55:59

为每个输入启动一个goroutine似乎是合理的,但我不确定您是否需要单独的goroutine来解析和发送。毕竟,其中一个只是在等待另一个完成。他们也可能是同一条猩猩。然后你不需要任何一个频道,因为他们只是让这两个猩猩沟通。

票数 3
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codereview.stackexchange.com/questions/23050

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档