github.com/xmplusdev/xray-core@v1.8.10/common/signal/done/done.go (about)

     1  package done
     2  
     3  import (
     4  	"sync"
     5  )
     6  
     7  // Instance is a utility for notifications of something being done.
     8  type Instance struct {
     9  	access sync.Mutex
    10  	c      chan struct{}
    11  	closed bool
    12  }
    13  
    14  // New returns a new Done.
    15  func New() *Instance {
    16  	return &Instance{
    17  		c: make(chan struct{}),
    18  	}
    19  }
    20  
    21  // Done returns true if Close() is called.
    22  func (d *Instance) Done() bool {
    23  	select {
    24  	case <-d.Wait():
    25  		return true
    26  	default:
    27  		return false
    28  	}
    29  }
    30  
    31  // Wait returns a channel for waiting for done.
    32  func (d *Instance) Wait() <-chan struct{} {
    33  	return d.c
    34  }
    35  
    36  // Close marks this Done 'done'. This method may be called multiple times. All calls after first call will have no effect on its status.
    37  func (d *Instance) Close() error {
    38  	d.access.Lock()
    39  	defer d.access.Unlock()
    40  
    41  	if d.closed {
    42  		return nil
    43  	}
    44  
    45  	d.closed = true
    46  	close(d.c)
    47  
    48  	return nil
    49  }