小伙伴们有没有觉得学习Golang很有意思?有意思就对了!今天就给大家带来《实现并发安全模板在 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 是并发安全的,为什么这一行会产生这种恐慌,我应该如何正确处理它?</p>
更新。
令人讨厌的函数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 中的方法和技巧》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!
本文内容来源于互联网,如有侵权请联系删除。
