github.com/gopherjs/gopherjs@v1.19.0-beta1.0.20240506212314-27071a8796e4/nosync/once.go (about) 1 package nosync 2 3 // Once is an object that will perform exactly one action. 4 type Once struct { 5 doing bool 6 done bool 7 } 8 9 // Do calls the function f if and only if Do is being called for the 10 // first time for this instance of Once. In other words, given 11 // 12 // var once Once 13 // 14 // if once.Do(f) is called multiple times, only the first call will invoke f, 15 // even if f has a different value in each invocation. A new instance of 16 // Once is required for each function to execute. 17 // 18 // Do is intended for initialization that must be run exactly once. Since f 19 // is niladic, it may be necessary to use a function literal to capture the 20 // arguments to a function to be invoked by Do: 21 // 22 // config.once.Do(func() { config.init(filename) }) 23 // 24 // If f causes Do to be called, it will panic. 25 // 26 // If f panics, Do considers it to have returned; future calls of Do return 27 // without calling f. 28 func (o *Once) Do(f func()) { 29 if o.done { 30 return 31 } 32 if o.doing { 33 panic("nosync: Do called within f") 34 } 35 o.doing = true 36 defer func() { 37 o.doing = false 38 o.done = true 39 }() 40 f() 41 }