douzi7711 2018-04-02 19:55
浏览 62
已采纳

无法在一个goroutine中写入并无限期地从另一个goroutine中读取

I am in the process of learning go, and I am having trouble with goroutines. Here is my code

package main

import (
    "fmt"
    "sync"
    "time"
)

var counter = 0
var wg = sync.WaitGroup{}

func main() {
    ticker := time.NewTicker(time.Second)
    go func() {
        for range ticker.C {
            // wg.Add(1)
            // defer wg.Done()
            counter++
            fmt.Println(counter)
            //wg.Done()
        }
    }()

    ticker2 := time.NewTicker(time.Second * 2)
    wg.Add(1)
    go func() {
        for range ticker2.C {
            //defer wg.Done()
            fmt.Println(counter)
        }
    }()
    wg.Wait()
}

Basically, I would like to have:

  • a global variable called counter
  • one goroutine that keeps updating this counter every one 1 second
  • another goroutine that keeps printing this counter every two seconds

Playground is here I tried to play with WaitGroup but I did not manage to have this working. With this level of code, I have the following warning:

WARNING: DATA RACE
Read at 0x0000011d8318 by goroutine 8:
  runtime.convT2E64()

Another question is this thread safe? I mean, can I safely use counter in the main method outside of the two groroutines?

  • 写回答

1条回答 默认 最新

  • dongsu1539 2018-04-02 23:19
    关注

    One way may be to send message to 2nd gorutine when it comes time to print.

    package main
    
    import (
        "fmt"
        "time"
    )
    
    func main() {
    
        fmt.Println("Start");
        counter := 0
    
        printChannel := make( chan int)
        done := make(chan struct{} )
    
        go func(done <-chan struct{}, printChannel chan<- int  ){
            timer := time.NewTicker(time.Second)
            bDone := false;
            for !bDone {
                select {
                case <-timer.C:
                    counter++
                    if counter%2 == 0 {
                        printChannel <- counter
                    }
                case <-done:
                    bDone=true
                }
            }
        }(done, printChannel)
    
        go func(done <-chan struct{}, printChannel <-chan int ){
            bDone:=false
            for !bDone{
                select {
                case n := <-printChannel:
                    fmt.Print(n, " ");
                case <-done:
                    bDone=true
                }
            }
        }(done,printChannel)
    
    
        //whatever logic to stop
        go func() {
            <- time.After(21*time.Second)
            done <- struct{}{}
        }()
    
        <-done
    
        fmt.Println("
    End");
    
    }
    

    Note that here there is 3rd gorutine just to finish the example

    Output:

    Start
    2 4 6 8 10 12 14 16 18 20 
    End
    

    To improve it, you can do it without bDone variable, you can stop Ticker and add appropriate message when gorutine exists. Or you may want to test 'break' with label to exit for loop.
    You can test effect when you use close(done) channel instead of sending message to it.
    Also, if you are ready to relax read/write order, you can remove printChannel and make 2nd gorutine use another ticker that pings every 2 seconds.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?