如何从并发映射写入恢复? [英] How to recover from concurrent map writes?

查看:160
本文介绍了如何从并发映射写入恢复?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从并发地图读取和地图写入的运行时恐慌中恢复?通常延迟恢复似乎不起作用。为什么会这样?



我知道你不应该在并发上下文中使用地图,但仍然是:如何在这里恢复?


$

 包主

导入时间

var m = make(map [string] string)

func main(){
go func(){
for {
m [x )=foo
}
}()
go {{b $ {$ b $ [x] =foo
}
}()

time.Sleep(1 * time.Second)
}

请添加恢复代码。 :)

解决方案

恢复功能在这里不起作用,因为您遇到的不是panicing状态。 b

Go 1.6添加轻量级并发地图检测误用于运行时: p>


运行时增加了对地图的并发滥用的轻量级尽力而为的检测。与往常一样,如果一个goroutine正在写入地图,则其他goroutine不应该同时读取或写入地图。 如果运行时检测到这种情况,它会打印诊断信息并使程序崩溃。了解更多问题的最佳方式是在比赛探测器,它将更可靠地识别比赛并给出更多细节。

你遇到的是运行时的故意崩溃,它不是 panic()调用的结果,即继续()调用延迟函数可能会停止。



除阻止并发滥用映射外,没有什么可以阻止它。如果你这样离开你的应用程序,它不会崩溃,你可能会在运行时遇到神秘的,未定义的行为。


How do you recover from a runtime panic on a "concurrent map read and map write"? The usual defer with recover doesn't seem to work. Why is that?

I know that you are not supposed to use maps in concurrent contexts, but still: how to recover here?

Example:

package main

import "time"

var m = make(map[string]string)

func main() {
    go func() {
        for {
            m["x"] = "foo"
        }
    }()
    go func() {
        for {
            m["x"] = "foo"
        }
    }()

    time.Sleep(1 * time.Second)
}

Please add recovery code. :)

解决方案

Recovering doesn't work here because what you experience is not a panicing state.

Go 1.6 added a lightweight concurrent misuse of maps detection to the runtime:

The runtime has added lightweight, best-effort detection of concurrent misuse of maps. As always, if one goroutine is writing to a map, no other goroutine should be reading or writing the map concurrently. If the runtime detects this condition, it prints a diagnosis and crashes the program. The best way to find out more about the problem is to run the program under the race detector, which will more reliably identify the race and give more detail.

What you experience is an intentional crash by the runtime, it's not the result of a panic() call that a recover() call in a deferred function could stop.

There's nothing you can do to stop that except prevent the concurrent misuse of maps. If you would leave your app like that and it wouldn't crash, you could experience mysterious, undefined behavior at runtime.

这篇关于如何从并发映射写入恢复?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆