当前位置:首页 > 文章列表 > Golang > Go问答 > 难以理解数据竞赛

难以理解数据竞赛

来源:stackoverflow 2024-03-03 16:21:26 0浏览 收藏

在Golang实战开发的过程中,我们经常会遇到一些这样那样的问题,然后要卡好半天,等问题解决了才发现原来一些细节知识点还是没有掌握好。今天golang学习网就整理分享《难以理解数据竞赛》,聊聊,希望可以帮助到正在努力赚钱的你。

问题内容

动机:我有一个巨大的 json 文件,我打算解析它并用它做一些事情。

现在,我确信会有一些库可以执行此操作,但我想自己执行此操作以更好地理解 go 的并发结构。

所以我的目标是使用 scanner 读取文件并将数据泵入 []byte chan,如下所示:

// not the actual code.
    for scanner.scan() {
       input <- []byte(scanner.text())
    }

我要求超过 1 个 go-routine 从 input chan 接收数据并解组 json 并返回结果(无论编组是否成功)并显示进度条

// not the actual code.
     for {
        bytes := <- input
        if err := json.unmarshal(bytes); err != nil {
          errorchan <- true
        } else {
           successchan <- true
        }
        progress <-  size_of_byte(bytes)
     }
    
      // now have other go-routine to handle errorchan, successchan and progress thing.

所有这些在纸上看起来都是合乎逻辑的,但是当我设法组装代码(如下所示)时,我看到了数据争用,并且我尽力了解数据争用是如何发生的,但无法理解(因为我删除了我们认为的其他一些数据争用)存在于前面的代码中)

workers 0xc0000c2000
 completed 0.000000==================
warning: data race
read at 0x00c0000c2048 by goroutine 8:
  mongo_import/race-d.readfile()
      /users/admin/documents/goproject/src/mongo_import/race-d/main.go:197 +0x6ff
  mongo_import/race-d.testreadjson()
      /users/admin/documents/goproject/src/mongo_import/race-d/main_test.go:8 +0x47
  testing.trunner()
      /usr/local/cellar/go/1.13.7/libexec/src/testing/testing.go:909 +0x199

previous write at 0x00c0000c2048 by goroutine 12:
  mongo_import/race-d.(*worker).tracksuccess()
      /users/admin/documents/goproject/src/mongo_import/race-d/main.go:103 +0xc0

goroutine 8 (running) created at:
  testing.(*t).run()
      /usr/local/cellar/go/1.13.7/libexec/src/testing/testing.go:960 +0x651
  testing.runtests.func1()
      /usr/local/cellar/go/1.13.7/libexec/src/testing/testing.go:1202 +0xa6
  testing.trunner()
      /usr/local/cellar/go/1.13.7/libexec/src/testing/testing.go:909 +0x199
  testing.runtests()
      /usr/local/cellar/go/1.13.7/libexec/src/testing/testing.go:1200 +0x521
  testing.(*m).run()
      /usr/local/cellar/go/1.13.7/libexec/src/testing/testing.go:1117 +0x2ff
  main.main()
      _testmain.go:44 +0x223

goroutine 12 (running) created at:
  mongo_import/race-d.(*worker).start()
      /users/admin/documents/goproject/src/mongo_import/race-d/main.go:72 +0x15f
==================
--- fail: testreadjson (1.18s)
    testing.go:853: race detected during execution of test
fail
fail    mongo_import/race-d 1.192s
fail
  • 测试包中的数据竞争对我来说是新事物。

  • 但我无法理解为什么这会导致数据竞争(这对我来说毫无意义)

    previous write at 0x00c0000c2048 by goroutine 12:
    mongo_import/race-d.(*worker).tracksuccess()
        /users/admin/documents/goproject/src/mongo_import/race-d/main.go:103 +0xc0
    
     goroutine 12 (running) created at:
    mongo_import/race-d.(*worker).start()
        /users/admin/documents/goproject/src/mongo_import/race-d/main.go:72 +0x15f

代码:

代码如下

package main
    
    import (
        "bufio"
        "encoding/binary"
        "encoding/json"
        "fmt"
        "log"
        "os"
        "sync"
        "time"
    )
    
    // thread that does that job of unmarshal
    type thread struct {
        w *worker
    }
    
    // run the individual thread and process the bytes
    // read for worter.input chan
    func (thread thread) run() {
        for {
            bytes, ok := <-thread.w.input
            if !ok {
                return
            }
    
            var data map[string]interface{}
            if err := json.unmarshal(bytes, &data); err != nil {
                thread.w.errorchan <- true
            } else {
                thread.w.successchan <- true
            }
    
            thread.w.progress <- int64(binary.size(bytes))
            // do other thing
            // like insert in db etc.
        }
    }
    
    // worker that
    type worker struct {
        errmutex      sync.mutex
        succmutex     sync.mutex
        progmutex     sync.mutex
        wg            sync.waitgroup
        done          bool
        workers       int
        filesize      int64
        completedbyte int64
        errorcount    int
        successcount  int
        input         chan []byte
        progress      chan int64
        errorchan     chan bool
        successchan   chan bool
    }
    
    // newworker
    func newworker(count int) *worker {
        return &worker{workers: count}
    }
    
    // start the worker
    func (w *worker) start() {
        fmt.printf("workers %p\n", w)
        w.wg.add(1)
        go w.display()
        w.wg.add(1)
        go w.trackprogress()
        w.wg.add(1)
        go w.tracksuccess()
        w.wg.add(1)
        go w.trackerror()
        w.wg.add(1)
        go w.spawn()
        w.wg.wait()
    }
    
    // add the error count
    func (w *worker) trackerror() {
        w.wg.done()
        for {
            _, ok := <-w.errorchan
            if !ok {
                return
            }
            w.errmutex.lock()
            w.errorcount = w.errorcount + 1
            w.errmutex.unlock()
        }
    }
    
    // add the success count
    func (w *worker) tracksuccess() {
        defer w.wg.done()
        for {
            _, ok := <-w.successchan
            if !ok {
                return
            }
            w.succmutex.lock()
            w.successcount += 1
            w.succmutex.unlock()
        }
    }
    
    // spawn individual thread to process the bytes
    func (w *worker) spawn() {
        defer w.wg.done()
        defer w.clean()
        var wg sync.waitgroup
        for i := 0; i < w.workers; i++ {
            wg.add(1)
            go func() {
                defer wg.done()
                thread{w: w}.run()
            }()
        }
    
        wg.wait()
    
    }
    
    // close the other open chan
    func (w *worker) clean() {
        close(w.errorchan)
        close(w.successchan)
        close(w.progress)
    }
    
    // close the input chan
    func (w *worker) done() {
        close(w.input)
    }
    
    // sum the total byte we have processed
    func (w *worker) trackprogress() {
        defer w.wg.done()
        for {
            read, ok := <-w.progress
            if !ok {
                w.done = true
                return
            }
            w.progmutex.lock()
            w.completedbyte += read
            w.progmutex.unlock()
    
        }
    }
    
    // display the progress bar
    func (w *worker) display() {
        defer w.wg.done()
        for !w.done {
            w.progmutex.lock()
            percentage := (float64(w.completedbyte) / float64(w.filesize)) * 100
            w.progmutex.unlock()
            fmt.printf("\r completed %f", percentage)
            time.sleep(5 * time.second)
        }
    }
    
    func readfile(path string) map[string]int {
        handler, err := os.open(path)
        if err != nil {
            log.fatal(err)
        }
        defer handler.close()
        worker := &worker{workers: 2}
        worker.input = make(chan []byte, 2)
        worker.progress = make(chan int64, 1)
        worker.errorchan = make(chan bool, 1)
        worker.successchan = make(chan bool, 1)
    
        if fi, err := handler.stat(); err != nil {
            log.fatal(err)
        } else {
            worker.filesize = fi.size()
        }
    
        scanner := bufio.newscanner(handler)
        go worker.start()
        for scanner.scan() {
            worker.input <- []byte(scanner.text())
        }
    
        worker.done()
        if err := scanner.err(); err != nil {
            log.fatal(err)
            return nil
        }
    
        return map[string]int{
            "error":   worker.errorcount,
            "success": worker.successcount,
        }
    }
    
    func main() {
        readfile("dump.json")
    }

和测试代码

package main // main_test.go
    
    import (
        "testing"
    )
    
    func testreadjson(t *testing.t) {
        data := readfile("dump2.json")
        if data == nil {
            t.error("we got a nil data")
        }
    }

这里是示例 dump2.json 数据

{"name": "tutorialspoint10"}
{"name":"tutorialspoint2", "age": 15}
{"name":"tutorialspoint3", "age": 25}
{"name":"tutorialspoint4", "age": 28}
{"name":"tutorialspoint5", "age": 40}
{"name": "tutorialspoint6"}
{"name":"tutorialspoint8", "age": 7}
{"name":"tutorialspoint4", "age": 55}
{"name":"tutorialspoint1","age":4}
{"name":"tutorialspoint2"}

最后,我知道这里发布的代码必须是简约的,但我尽力保持代码简约(从原始项目中提取)。我不确定如何(或目前有能力)进一步最小化它。


解决方案


您需要在 main.go:197 行添加读锁

“成功”:worker.successCount,

正如日志所说。您尝试读取,而另一个 go 例程尝试写入。 /Users/admin/Documents/goProject/src/mongo_import/race-d/main.go:197

简短说明:

https://dev.to/wagslane/golang-mutexes-what-is-rwmutex-for-57a0

在这种情况下使用 Atomic 可能会更好。 https://gobyexample.com/atomic-counters

理论要掌握,实操不能落!以上关于《难以理解数据竞赛》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

版本声明
本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
如何为不同时间区域设置多个定时任务如何为不同时间区域设置多个定时任务
上一篇
如何为不同时间区域设置多个定时任务
Squirrel 在错误处理时添加了
下一篇
Squirrel 在错误处理时添加了"sql:"前缀,导致出现问题
查看更多
最新文章
查看更多
课程推荐
  • 前端进阶之JavaScript设计模式
    前端进阶之JavaScript设计模式
    设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
    542次学习
  • GO语言核心编程课程
    GO语言核心编程课程
    本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
    508次学习
  • 简单聊聊mysql8与网络通信
    简单聊聊mysql8与网络通信
    如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
    497次学习
  • JavaScript正则表达式基础与实战
    JavaScript正则表达式基础与实战
    在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
    487次学习
  • 从零制作响应式网站—Grid布局
    从零制作响应式网站—Grid布局
    本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
    484次学习
查看更多
AI推荐
  • 笔灵AI生成答辩PPT:高效制作学术与职场PPT的利器
    笔灵AI生成答辩PPT
    探索笔灵AI生成答辩PPT的强大功能,快速制作高质量答辩PPT。精准内容提取、多样模板匹配、数据可视化、配套自述稿生成,让您的学术和职场展示更加专业与高效。
    24次使用
  • 知网AIGC检测服务系统:精准识别学术文本中的AI生成内容
    知网AIGC检测服务系统
    知网AIGC检测服务系统,专注于检测学术文本中的疑似AI生成内容。依托知网海量高质量文献资源,结合先进的“知识增强AIGC检测技术”,系统能够从语言模式和语义逻辑两方面精准识别AI生成内容,适用于学术研究、教育和企业领域,确保文本的真实性和原创性。
    38次使用
  • AIGC检测服务:AIbiye助力确保论文原创性
    AIGC检测-Aibiye
    AIbiye官网推出的AIGC检测服务,专注于检测ChatGPT、Gemini、Claude等AIGC工具生成的文本,帮助用户确保论文的原创性和学术规范。支持txt和doc(x)格式,检测范围为论文正文,提供高准确性和便捷的用户体验。
    37次使用
  • 易笔AI论文平台:快速生成高质量学术论文的利器
    易笔AI论文
    易笔AI论文平台提供自动写作、格式校对、查重检测等功能,支持多种学术领域的论文生成。价格优惠,界面友好,操作简便,适用于学术研究者、学生及论文辅导机构。
    48次使用
  • 笔启AI论文写作平台:多类型论文生成与多语言支持
    笔启AI论文写作平台
    笔启AI论文写作平台提供多类型论文生成服务,支持多语言写作,满足学术研究者、学生和职场人士的需求。平台采用AI 4.0版本,确保论文质量和原创性,并提供查重保障和隐私保护。
    41次使用
微信登录更方便
  • 密码登录
  • 注册账号
登录即同意 用户协议隐私政策
返回登录
  • 重置密码