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 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动