...
Run Format

Source file src/sync/once.go

Documentation: sync

     1  // Copyright 2009 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package sync
     6  
     7  import (
     8  	"sync/atomic"
     9  )
    10  
    11  // Once is an object that will perform exactly one action.
    12  type Once struct {
    13  	m    Mutex
    14  	done uint32
    15  }
    16  
    17  // Do calls the function f if and only if Do is being called for the
    18  // first time for this instance of Once. In other words, given
    19  // 	var once Once
    20  // if once.Do(f) is called multiple times, only the first call will invoke f,
    21  // even if f has a different value in each invocation. A new instance of
    22  // Once is required for each function to execute.
    23  //
    24  // Do is intended for initialization that must be run exactly once. Since f
    25  // is niladic, it may be necessary to use a function literal to capture the
    26  // arguments to a function to be invoked by Do:
    27  // 	config.once.Do(func() { config.init(filename) })
    28  //
    29  // Because no call to Do returns until the one call to f returns, if f causes
    30  // Do to be called, it will deadlock.
    31  //
    32  // If f panics, Do considers it to have returned; future calls of Do return
    33  // without calling f.
    34  //
    35  func (o *Once) Do(f func()) {
    36  	if atomic.LoadUint32(&o.done) == 1 {
    37  		return
    38  	}
    39  	// Slow-path.
    40  	o.m.Lock()
    41  	defer o.m.Unlock()
    42  	if o.done == 0 {
    43  		defer atomic.StoreUint32(&o.done, 1)
    44  		f()
    45  	}
    46  }
    47  

View as plain text