...

Source file src/github.com/redis/go-redis/v9/internal/once.go

Documentation: github.com/redis/go-redis/v9/internal

     1  /*
     2  Copyright 2014 The Camlistore Authors
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8       http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package internal
    18  
    19  import (
    20  	"sync"
    21  	"sync/atomic"
    22  )
    23  
    24  // A Once will perform a successful action exactly once.
    25  //
    26  // Unlike a sync.Once, this Once's func returns an error
    27  // and is re-armed on failure.
    28  type Once struct {
    29  	m    sync.Mutex
    30  	done uint32
    31  }
    32  
    33  // Do calls the function f if and only if Do has not been invoked
    34  // without error for this instance of Once.  In other words, given
    35  //
    36  //	var once Once
    37  //
    38  // if once.Do(f) is called multiple times, only the first call will
    39  // invoke f, even if f has a different value in each invocation unless
    40  // f returns an error.  A new instance of Once is required for each
    41  // function to execute.
    42  //
    43  // Do is intended for initialization that must be run exactly once.  Since f
    44  // is niladic, it may be necessary to use a function literal to capture the
    45  // arguments to a function to be invoked by Do:
    46  //
    47  //	err := config.once.Do(func() error { return config.init(filename) })
    48  func (o *Once) Do(f func() error) error {
    49  	if atomic.LoadUint32(&o.done) == 1 {
    50  		return nil
    51  	}
    52  	// Slow-path.
    53  	o.m.Lock()
    54  	defer o.m.Unlock()
    55  	var err error
    56  	if o.done == 0 {
    57  		err = f()
    58  		if err == nil {
    59  			atomic.StoreUint32(&o.done, 1)
    60  		}
    61  	}
    62  	return err
    63  }
    64  

View as plain text