github.com/aergoio/aergo@v1.3.1/types/peerstate_test.go (about)

     1  package types
     2  
     3  import (
     4  	"sync"
     5  	"sync/atomic"
     6  	"testing"
     7  
     8  	"github.com/aergoio/aergo-lib/log"
     9  	"github.com/stretchr/testify/assert"
    10  )
    11  
    12  func TestPeerState_Get(t *testing.T) {
    13  	wg := sync.WaitGroup{}
    14  
    15  	concurrentCnt := 100
    16  	epoch := 100
    17  	logger := log.NewLogger("test")
    18  
    19  	logger.Info().Msg("================= Without atomic ops.")
    20  	target := STARTING
    21  	wg.Add(concurrentCnt)
    22  	for i := 0; i < concurrentCnt; i++ {
    23  		go func(in int) {
    24  			for j := 0; j < epoch; j++ {
    25  				//				logger.Infof("#%03d old state value is %d", in, int32(target))
    26  				target++
    27  				//				logger.Infof("#%03d new state is set to %d", in, PeerState(target))
    28  			}
    29  			wg.Done()
    30  		}(i)
    31  	}
    32  	wg.Wait()
    33  	logger.Info().Msgf("Expected %d , actual = %d", concurrentCnt*epoch, int32(target))
    34  	logger.Info().Msg("================= With atomic ops.")
    35  	var ocounter, ncounter [5]int32
    36  
    37  	target = STARTING
    38  	wg.Add(concurrentCnt)
    39  	for i := 0; i < concurrentCnt; i++ {
    40  		go func(in int) {
    41  			for j := 0; j < epoch; j++ {
    42  				newS := PeerState(j % 5)
    43  				oldS := target.SetAndGet(newS)
    44  				atomic.AddInt32(&ocounter[oldS], 1)
    45  				atomic.AddInt32(&ncounter[newS], 1)
    46  			}
    47  			wg.Done()
    48  		}(i)
    49  	}
    50  
    51  	wg.Wait()
    52  	oldS := target.SetAndGet(STARTING)
    53  	atomic.AddInt32(&ocounter[oldS], 1)
    54  	atomic.AddInt32(&ncounter[STARTING], 1)
    55  	for i := 0; i < 5; i++ {
    56  		assert.Equal(t, ocounter[i], ncounter[i])
    57  	}
    58  	logger.Info().Msgf("Values %v", ocounter)
    59  	logger.Info().Msg("Done")
    60  }