sync.Once 多次调用一次执行的方法
发表于:2026-11-03 作者:千家信息网编辑
千家信息网最后更新 2026年11月03日,本篇内容介绍了"sync.Once 多次调用一次执行的方法"的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所
千家信息网最后更新 2026年11月03日sync.Once 多次调用一次执行的方法
本篇内容介绍了"sync.Once 多次调用一次执行的方法"的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!
demo
package mainimport ( "fmt" "sync")func main() { var once sync.Once onceFunc := func() { fmt.Println("this func do once") } done := make(chan bool) for i := 0; i < 10; i++ { go func() { once.Do(onceFunc) done <- true }() } for i := 0; i < 10; i++ { <-done }}output
liqiongtao:test liqiongtao$ go run main.go this func do once
Once源码
// Copyright 2009 The Go Authors. All rights reserved.// Use of this source code is governed by a BSD-style// license that can be found in the LICENSE file.package syncimport ( "sync/atomic")// Once is an object that will perform exactly one action.type Once struct { m Mutex done uint32}// Do calls the function f if and only if Do is being called for the// first time for this instance of Once. In other words, given// var once Once// if once.Do(f) is called multiple times, only the first call will invoke f,// even if f has a different value in each invocation. A new instance of// Once is required for each function to execute.//// Do is intended for initialization that must be run exactly once. Since f// is niladic, it may be necessary to use a function literal to capture the// arguments to a function to be invoked by Do:// config.once.Do(func() { config.init(filename) })//// Because no call to Do returns until the one call to f returns, if f causes// Do to be called, it will deadlock.//// If f panics, Do considers it to have returned; future calls of Do return// without calling f.//func (o *Once) Do(f func()) { if atomic.LoadUint32(&o.done) == 1 { return } // Slow-path. o.m.Lock() defer o.m.Unlock() if o.done == 0 { defer atomic.StoreUint32(&o.done, 1) f() }}"sync.Once 多次调用一次执行的方法"的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注网站,小编将为大家输出更多高质量的实用文章!
方法
内容
更多
知识
实用
学有所成
接下来
困境
实际
情况
文章
案例
源码
编带
网站
行业
过程
高质量
学习
有关
数据库的安全要保护哪些东西
数据库安全各自的含义是什么
生产安全数据库录入
数据库的安全性及管理
数据库安全策略包含哪些
海淀数据库安全审计系统
建立农村房屋安全信息数据库
易用的数据库客户端支持安全管理
连接数据库失败ssl安全错误
数据库的锁怎样保障安全
互联网科技园
互联网加科技
互联网巨头反垄断金融科技
科技类互联网
互联网金融 科技
深圳互联网科技公司
互联网金融 金融科技
互联网科技视频
易通互联网络科技有限公司
互联网科技博客
互联网为啥属于高科技
辽宁互联网新科技
恒生互联网科技指数跳水
青海科技产业互联网发展
济南有互联网科技公司吗
富国互联网金融科技混合基金
普陀区互联网教育科技管理办法
版纳互联网科技选哪家
华人运通互联网科技公司
互联网科技自媒体灵感
互联网科技上市公司
沃里互联网科技
互联网高科技企业
重庆科技学院互联网
中国科技互联网公司收入
湖南诚度互联网科技有限公司
南通创西澳互联网科技有限公司
领航科技大厦互联网公司
互联网科技收购价值
互联网科技快速发展优美句子