github.com/aacfactory/fns@v1.2.86-0.20240310083819-80d667fc0a17/shareds/locker_test.go (about)

     1  /*
     2   * Copyright 2023 Wang Min Xiang
     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  
    18  package shareds_test
    19  
    20  import (
    21  	"fmt"
    22  	"github.com/aacfactory/fns/context"
    23  	"github.com/aacfactory/fns/shareds"
    24  	"sync"
    25  	"testing"
    26  	"time"
    27  )
    28  
    29  type N struct {
    30  	n int
    31  }
    32  
    33  func TestLocalLockers(t *testing.T) {
    34  	lockers := shareds.LocalLockers()
    35  	ctx := context.TODO()
    36  	wg := sync.WaitGroup{}
    37  	n := &N{
    38  		n: 0,
    39  	}
    40  	for i := 0; i < 10; i++ {
    41  		wg.Add(1)
    42  		go func(ctx context.Context, lockers shareds.Lockers, group *sync.WaitGroup, x *N) {
    43  			defer group.Done()
    44  			locker, getErr := lockers.Acquire(ctx, []byte("locker"), 2*time.Second)
    45  			if getErr != nil {
    46  				t.Errorf("%+v", getErr)
    47  				return
    48  			}
    49  			lockErr := locker.Lock(ctx)
    50  			if lockErr != nil {
    51  				t.Errorf("%+v", lockErr)
    52  				return
    53  			}
    54  			x.n++
    55  			fmt.Println(x.n)
    56  			_ = locker.Unlock(ctx)
    57  		}(ctx, lockers, &wg, n)
    58  	}
    59  	wg.Wait()
    60  }