github.com/pharosnet/flyline@v1.0.2/element.go (about)

     1  package flyline
     2  
     3  import (
     4  	"sync"
     5  	"time"
     6  )
     7  
     8  const (
     9  	eleStatusEmpty = int64(0)
    10  	eleStatusFull  = int64(1)
    11  )
    12  
    13  // Element of buffer.
    14  // with status about set and get
    15  type element struct {
    16  	value  interface{}
    17  	status int64
    18  	lock   *sync.Mutex
    19  }
    20  
    21  // set and make status to be full
    22  func (e *element) set(v interface{}) {
    23  	for {
    24  		e.lock.Lock()
    25  		if e.status == eleStatusEmpty {
    26  			e.value = v
    27  			e.status = eleStatusFull
    28  			e.lock.Unlock()
    29  			return
    30  		}
    31  		e.lock.Unlock()
    32  		time.Sleep(200 * time.Microsecond)
    33  	}
    34  }
    35  
    36  // get and make status to be empty
    37  func (e *element) pop() interface{} {
    38  	for {
    39  		e.lock.Lock()
    40  		if e.status == eleStatusFull {
    41  			v := e.value
    42  			e.status = eleStatusEmpty
    43  			e.lock.Unlock()
    44  			return v
    45  		}
    46  		e.lock.Unlock()
    47  		time.Sleep(200 * time.Microsecond)
    48  	}
    49  }