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

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

问题描述

如何从并发映射读取和映射写入"的运行时恐慌中恢复?通常的带有恢复的延迟似乎不起作用.这是为什么?

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?

示例:

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)
}

请添加恢复代码.:)

推荐答案

恢复在这里不起作用,因为您所经历的不是恐慌状态.

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

Go 1.6 添加了一个轻量级并发误用地图检测到运行时:

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

运行时添加了轻量级、尽力而为的并发误用地图检测.与往常一样,如果一个 goroutine 正在写入地图,则没有其他 goroutine 应该同时读取或写入地图.如果运行时检测到这种情况,它会打印诊断信息并使程序崩溃. 要了解有关问题的更多信息,最好的方法是在 种族检测器,它将更可靠地识别种族并提供更多细节.

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.

您遇到的是运行时故意崩溃,这不是 panic() 调用的结果,而是 recover()延迟函数中的调用可能会停止.

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天全站免登陆