...

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  //
		13  // A Once must not be copied after first use.
		14  type Once struct {
		15  	// done indicates whether the action has been performed.
		16  	// It is first in the struct because it is used in the hot path.
		17  	// The hot path is inlined at every call site.
		18  	// Placing done first allows more compact instructions on some architectures (amd64/386),
		19  	// and fewer instructions (to calculate offset) on other architectures.
		20  	done uint32
		21  	m		Mutex
		22  }
		23  
		24  // Do calls the function f if and only if Do is being called for the
		25  // first time for this instance of Once. In other words, given
		26  // 	var once Once
		27  // if once.Do(f) is called multiple times, only the first call will invoke f,
		28  // even if f has a different value in each invocation. A new instance of
		29  // Once is required for each function to execute.
		30  //
		31  // Do is intended for initialization that must be run exactly once. Since f
		32  // is niladic, it may be necessary to use a function literal to capture the
		33  // arguments to a function to be invoked by Do:
		34  // 	config.once.Do(func() { config.init(filename) })
		35  //
		36  // Because no call to Do returns until the one call to f returns, if f causes
		37  // Do to be called, it will deadlock.
		38  //
		39  // If f panics, Do considers it to have returned; future calls of Do return
		40  // without calling f.
		41  //
		42  func (o *Once) Do(f func()) {
		43  	// Note: Here is an incorrect implementation of Do:
		44  	//
		45  	//	if atomic.CompareAndSwapUint32(&o.done, 0, 1) {
		46  	//		f()
		47  	//	}
		48  	//
		49  	// Do guarantees that when it returns, f has finished.
		50  	// This implementation would not implement that guarantee:
		51  	// given two simultaneous calls, the winner of the cas would
		52  	// call f, and the second would return immediately, without
		53  	// waiting for the first's call to f to complete.
		54  	// This is why the slow path falls back to a mutex, and why
		55  	// the atomic.StoreUint32 must be delayed until after f returns.
		56  
		57  	if atomic.LoadUint32(&o.done) == 0 {
		58  		// Outlined slow-path to allow inlining of the fast-path.
		59  		o.doSlow(f)
		60  	}
		61  }
		62  
		63  func (o *Once) doSlow(f func()) {
		64  	o.m.Lock()
		65  	defer o.m.Unlock()
		66  	if o.done == 0 {
		67  		defer atomic.StoreUint32(&o.done, 1)
		68  		f()
		69  	}
		70  }
		71  

View as plain text