...

Source file src/pkg/sync/once.go

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

View as plain text