对于从全局的角度只需要运行一次的代码,比如全局初化操始作,go语言提供了一个Once类型来保证全局的唯一性操作。
typeOnce
Once is an object that will perform exactly one action.
- type Once struct {
- // contains filtered or unexported fields
- }
func (*Once)Do
- func (o *Once) Do(f func())
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
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.
- var once Once
大体意思是说,一个Once对象在全局范围内只会执行一个操作。
e.g. 单线程环境下演示Once的唯一性
- package@H_403_41@ main
- import@H_403_41@ (
- @H_403_41@"fmt"
- @H_403_41@"sync"
- )
- }
- }
- }
- @H_403_41@once.Do(f1)
- @H_403_41@once.Do(f2)
- @H_403_41@once.Do(f3)
- }
运行:
C:/go/bin/go.exe run test.go [E:/project/go/lx/src]
This is f1 function
从上面的运行结果可以看出,只有f1函数被调用了。一旦一个Once对象的Do方法被调用,那么接下来对该Once对象Do方法的调用都将不会执行。
e.g.多线程环境下演示Once的唯一性
- package@H_403_41@ main
- import@H_403_41@ (
- @H_403_41@"fmt"
- @H_403_41@"sync"
- @H_403_41@"time"
- )
- @H_403_41@time.Sleep(1e9)
- @H_403_41@fmt.Print(".")
- @H_403_41@}
- }
- @H_403_41@once.Do(setup)
- @H_403_41@fmt.Println(a)
- @H_403_41@wg.Done()
- }
- @H_403_41@wg.Add(2)
- @H_403_41@wg.Wait()
- }
运行:
C:/go/bin/go.exe run test2.go [E:/project/go/lx/src]
setup begins.
..........
setup ends.
hello
hello
这里需要说明一点:在首次调用once.Do()方法时,其内部会加锁,阻塞其他goroutine对此Do方法的调用,直至全局唯一性操作调用结束,才会释放内部的锁。