douge3492 2014-09-24 12:02
浏览 38
已采纳

如何实现弹出->做某事->使用goroutines推送队列

I have a queue and I would like to perform the following operations:

  • pop the first element

  • If the element is even, push element +1

This should go on until the queue is empty; furthermore I want to use multiple goroutines at the same time.

I am able to do for a single goroutine, but as soon as I add a while everything goes wrong, since it appears that too many goroutines are created. Even putting a else {return} will not solve the problem. Side question: why not? I get the errors:

syntax error: unexpected semicolon or newline before else
syntax error: unexpected }

Link to Playground

var list = []int{0, 1, 2, 3}

var mutex = &sync.Mutex{}

func pop(out chan int) {
    mutex.Lock()
    element := list[0]
    fmt.Println("element is ", element)
    list = list[1:]
    mutex.Unlock()
    out <- element
}

func push(in chan int) {
    for element := range in {
        if element%2 == 0 {
            mutex.Lock()
            list = append(list, element+1)
            fmt.Println("New list is ", list)
            mutex.Unlock()
        }
    }
}

func main() {
    out := make(chan int)
    fmt.Println("MAIN")

//  for len(list) != 0 {
    go pop(out)
    go push(out)
//}
    time.Sleep(2)
}
  • 写回答

2条回答 默认 最新

  • 普通网友 2014-09-24 13:07
    关注

    Multiple problems with your code.

    • else is always on the same line as if's closing brace. Please read the Spec on this.

    • time.Sleep takes time.Duration as its argument, which is in nanoseconds. If you want to sleep for 2 seconds, use time.Sleep(2*time.Second).

    • for range in push is not needed.

    • Your for for just spawns millions of goroutines over and over. Goroutintes are lightweight, but not free. Add some kind of synchronisation mechanism to control how many goroutines you are running.

    Here is a slightly better version. It works, even though using time.Sleep as a synchronisation mechanism is something you should never do.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上