jjzjj

go - 如果没有互斥体,并发处理 slice 无法按预期工作

coder 2024-07-13 原文

函数 WithMutexWithoutMutex 给出了不同的结果。

WithoutMutex 实现正在丢失值,即使我设置了 Waitgroup

有什么问题吗?

Do not run on Playground

附言我使用的是 Windows 10 和 Go 1.8.1

package main

import (
    "fmt"
    "sync"
)

var p = fmt.Println

type MuType struct {
    list []int
    *sync.RWMutex
}

var muData *MuType
var data *NonMuType

type NonMuType struct {
    list []int
}

func (data *MuType) add(i int, wg *sync.WaitGroup) {
    data.Lock()
    defer data.Unlock()
    data.list = append(data.list, i)
    wg.Done()

}

func (data *MuType) read() []int {
    data.RLock()
    defer data.RUnlock()
    return data.list
}

func (nonmu *NonMuType) add(i int, wg *sync.WaitGroup) {
    nonmu.list = append(nonmu.list, i)
    wg.Done()

}

func (nonmu *NonMuType) read() []int {
    return nonmu.list
}

func WithoutMutex() {
    nonmu := &NonMuType{}
    nonmu.list = make([]int, 0)
    var wg = sync.WaitGroup{}
    for i := 0; i < 10; i++ {
        wg.Add(1)
        go nonmu.add(i, &wg)

    }
    wg.Wait()
    data = nonmu
    p(data.read())
}

func WithMutex() {
    mtx := &sync.RWMutex{}
    withMu := &MuType{list: make([]int, 0)}
    withMu.RWMutex = mtx
    var wg = sync.WaitGroup{}
    for i := 0; i < 10; i++ {
        wg.Add(1)
        go withMu.add(i, &wg)
    }
    wg.Wait()
    muData = withMu
    p(muData.read())
}

func stressTestWOMU(max int) {
    p("Without Mutex")
    for ii := 0; ii < max; ii++ {
        WithoutMutex()
    }
}

func stressTest(max int) {
    p("With Mutex")
    for ii := 0; ii < max; ii++ {
        WithMutex()
    }
}

func main() {
    stressTestWOMU(20)
    stressTest(20)
}

最佳答案

slice 对于并发写入是不安全的,所以我一点也不惊讶 WithoutMutex 看起来根本不一致,并且已经删除了项目。

WithMutex 版本一直有 10 个项目,但顺序困惑。这也是意料之中的,因为互斥量保护它,以便一次只能追加一个。虽然无法保证哪个 goroutine 将以哪个顺序运行,因此这是一场竞赛,看哪个快速生成的 goroutine 将首先附加。

WaitGroup 不做任何事情来控制访问或强制排序。它只是在最后提供一个信号,表明一切都已完成。

关于go - 如果没有互斥体,并发处理 slice 无法按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43799555/

有关go - 如果没有互斥体,并发处理 slice 无法按预期工作的更多相关文章

  1. ruby-on-rails - 由于 "wkhtmltopdf",PDFKIT 显然无法正常工作 - 2

    我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-

  2. ruby-on-rails - 'compass watch' 是如何工作的/它是如何与 rails 一起使用的 - 2

    我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t

  3. ruby - 如何指定 Rack 处理程序 - 2

    Rackup通过Rack的默认处理程序成功运行任何Rack应用程序。例如:classRackAppdefcall(environment)['200',{'Content-Type'=>'text/html'},["Helloworld"]]endendrunRackApp.new但是当最后一行更改为使用Rack的内置CGI处理程序时,rackup给出“NoMethodErrorat/undefinedmethod`call'fornil:NilClass”:Rack::Handler::CGI.runRackApp.newRack的其他内置处理程序也提出了同样的反对意见。例如Rack

  4. ruby - 难道Lua没有和Ruby的method_missing相媲美的东西吗? - 2

    我好像记得Lua有类似Ruby的method_missing的东西。还是我记错了? 最佳答案 表的metatable的__index和__newindex可以用于与Ruby的method_missing相同的效果。 关于ruby-难道Lua没有和Ruby的method_missing相媲美的东西吗?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/7732154/

  5. ruby-on-rails - 如果为空或不验证数值,则使属性默认为 0 - 2

    我希望我的UserPrice模型的属性在它们为空或不验证数值时默认为0。这些属性是tax_rate、shipping_cost和price。classCreateUserPrices8,:scale=>2t.decimal:tax_rate,:precision=>8,:scale=>2t.decimal:shipping_cost,:precision=>8,:scale=>2endendend起初,我将所有3列的:default=>0放在表格中,但我不想要这样,因为它已经填充了字段,我想使用占位符。这是我的UserPrice模型:classUserPrice回答before_val

  6. ruby-on-rails - rails 目前在重启后没有安装 - 2

    我有一个奇怪的问题:我在rvm上安装了ruby​​onrails。一切正常,我可以创建项目。但是在我输入“railsnew”时重新启动后,我有“程序'rails'当前未安装。”。SystemUbuntu12.04ruby-v"1.9.3p194"gemlistactionmailer(3.2.5)actionpack(3.2.5)activemodel(3.2.5)activerecord(3.2.5)activeresource(3.2.5)activesupport(3.2.5)arel(3.0.2)builder(3.0.0)bundler(1.1.4)coffee-rails(

  7. ruby - 无法让 RSpec 工作—— 'require' : cannot load such file - 2

    我花了三天的时间用头撞墙,试图弄清楚为什么简单的“rake”不能通过我的规范文件。如果您遇到这种情况:任何文件夹路径中都不要有空格!。严重地。事实上,从现在开始,您命名的任何内容都没有空格。这是我的控制台输出:(在/Users/*****/Desktop/LearningRuby/learn_ruby)$rake/Users/*******/Desktop/LearningRuby/learn_ruby/00_hello/hello_spec.rb:116:in`require':cannotloadsuchfile--hello(LoadError) 最佳

  8. ruby - 在没有 sass 引擎的情况下使用 sass 颜色函数 - 2

    我想在一个没有Sass引擎的类中使用Sass颜色函数。我已经在项目中使用了sassgem,所以我认为搭载会像以下一样简单:classRectangleincludeSass::Script::FunctionsdefcolorSass::Script::Color.new([0x82,0x39,0x06])enddefrender#hamlengineexecutedwithcontextofself#sothatwithintemlateicouldcall#%stop{offset:'0%',stop:{color:lighten(color)}}endend更新:参见上面的#re

  9. ruby-on-rails - 如果 Object::try 被发送到一个 nil 对象,为什么它会起作用? - 2

    如果您尝试在Ruby中的nil对象上调用方法,则会出现NoMethodError异常并显示消息:"undefinedmethod‘...’fornil:NilClass"然而,有一个tryRails中的方法,如果它被发送到一个nil对象,它只返回nil:require'rubygems'require'active_support/all'nil.try(:nonexisting_method)#noNoMethodErrorexceptionanymore那么try如何在内部工作以防止该异常? 最佳答案 像Ruby中的所有其他对象

  10. ruby-on-rails - rspec should have_select ('cars' , :options => ['volvo' , 'saab' ] 不工作 - 2

    关闭。这个问题需要detailsorclarity.它目前不接受答案。想改进这个问题吗?通过editingthispost添加细节并澄清问题.关闭8年前。Improvethisquestion在首页我有:汽车:VolvoSaabMercedesAudistatic_pages_spec.rb中的测试代码:it"shouldhavetherightselect"dovisithome_pathit{shouldhave_select('cars',:options=>['volvo','saab','mercedes','audi'])}end响应是rspec./spec/request

随机推荐