首页 > 后端开发 > Golang > 正文

Go 中的并发安全模板:我该怎么做?

WBOY
发布: 2024-02-08 21:50:10
转载
1007人浏览过

go 中的并发安全模板:我该怎么做?

Go 中的并发安全模板是一个关键问题,对于需要在并发环境下进行操作的程序来说,确保数据的安全性是至关重要的。在处理并发时,我们需要采取一些措施来保护共享资源,避免出现竞态条件和数据竞争。在这篇文章中,我将向大家介绍一些常用的并发安全模板,帮助你理解并发安全的概念,并提供一些实践中的建议。无论是初学者还是有经验的开发者,都可以从中受益。让我们一起来探讨如何在 Go 中实现并发安全!

问题内容

我有以下电话:

import (
  "text/template"
)

//...

template.new(filepath.base(name)).funcs(templatefunctions).parse(string(asset))
登录后复制

在多个 go 例程中同时调用, 这又会导致以下恐慌:

fatal error: concurrent map iteration and map write
登录后复制

这是回溯:

goroutine 140 [running]:
text/template.addvaluefuncs(0xc00188e000?, 0xc00188e000?)
        [...]/go/src/text/template/funcs.go:88 +0x76
[...]/modules/template.loadembeddedtemplates({0x38ff6cb?, 0xc001cf8060?})
        [...]/src/modules/template/configbased.go:163 +0x749
登录后复制

src/modules/template/configbased.go:163 上的行 上面引用了。它是 template.new(...)

周围的函数是从 goroutine 中同时调用的。

这是来自 go/src/text/template/funcs.go:88 的代码是否有帮助:

// addvaluefuncs adds to values the functions in funcs, converting them to reflect.values.
func addvaluefuncs(out map[string]reflect.value, in funcmap) {
    for name, fn := range in {
        if !goodname(name) {
            panic(fmt.errorf("function name %q is not a valid identifier", name))
        }
        v := reflect.valueof(fn)
        if v.kind() != reflect.func {
            panic("value for " + name + " not a function")
        }
        if !goodfunc(v.type()) {
            panic(fmt.errorf("can't install method/function %q with %d results", name, v.type().numout()))
        }
        out[name] = v
    }
}
登录后复制

如果 template.new 是并发安全的,为什么这一行会产生这种恐慌,我应该如何正确处理它?

更新。

百度智能云·曦灵
百度智能云·曦灵

百度旗下的AI数字人平台

百度智能云·曦灵 83
查看详情 百度智能云·曦灵

令人讨厌的函数loadembeddedtemplates的代码:

func loadEmbeddedTemplates(templateFile string) (*template.Template, error) {
    var t *template.Template

    templateFile = filepath.Join("share", "templates", filepath.Base(templateFile))
    dir := filepath.Dir(templateFile)
    names := assets.GetAssetNames()

    // All templates except + the last one at the end
    filteredNames := []string{}

    for _, name := range names {
        if !strings.HasPrefix(name, dir+"/") || !strings.HasSuffix(name, ".tmpl") {
            continue
        }

        if name != templateFile {
            filteredNames = append(filteredNames, name)
        }
    }

    filteredNames = append(filteredNames, templateFile)

    for _, name := range filteredNames {
        asset, err := assets.GetAsset(name)
        if err != nil {
            return nil, err
        }

        if t == nil {
            t, err = template.New(filepath.Base(name)).Funcs(templateFunctions).Parse(string(asset))
        } else {
            t, err = t.New(filepath.Base(name)).Parse(string(asset))
        }

        if err != nil {
            return nil, err
        }
    }

    return t, nil
}
登录后复制

该函数只是依次加载 share/templates/ 中的所有模板

解决方法

您的 loadEmbeddedTemplates() 函数访问 templateFunctions 变量,将其传递给 Template.Funcs() ,后者显然会读取它(将迭代它)。

并且您可能会在另一个 goroutine 中同时填充它。因此,并发映射写入错误。对它的访问必须同步。

如果可能,请先填充它,然后才开始使用它(将其传递给 Template.Funcs())。这样就不需要额外的同步或锁定(并发只读总是可以的)。

以上就是Go 中的并发安全模板:我该怎么做?的详细内容,更多请关注php中文网其它相关文章!

相关标签:
最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:stackoverflow网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
热门推荐
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号