github.com/grailbio/base@v0.0.11/sync/ctxsync/cond_test.go (about)

     1  // Copyright 2018 GRAIL, Inc. All rights reserved.
     2  // Use of this source code is governed by the Apache 2.0
     3  // license that can be found in the LICENSE file.
     4  
     5  package ctxsync
     6  
     7  import (
     8  	"context"
     9  	"sync"
    10  	"testing"
    11  )
    12  
    13  func TestContextCond(t *testing.T) {
    14  	var (
    15  		mu          sync.Mutex
    16  		cond        = NewCond(&mu)
    17  		start, done sync.WaitGroup
    18  	)
    19  	const N = 100
    20  	start.Add(N)
    21  	done.Add(N)
    22  	errs := make([]error, N)
    23  	for i := 0; i < N; i++ {
    24  		go func(idx int) {
    25  			mu.Lock()
    26  			start.Done()
    27  			if err := cond.Wait(context.Background()); err != nil {
    28  				errs[idx] = err
    29  			}
    30  			mu.Unlock()
    31  			done.Done()
    32  		}(i)
    33  	}
    34  
    35  	start.Wait()
    36  	mu.Lock()
    37  	cond.Broadcast()
    38  	mu.Unlock()
    39  	done.Wait()
    40  	for _, err := range errs {
    41  		if err != nil {
    42  			t.Fatal(err)
    43  		}
    44  	}
    45  }
    46  
    47  func TestContextCondErr(t *testing.T) {
    48  	var (
    49  		mu   sync.Mutex
    50  		cond = NewCond(&mu)
    51  	)
    52  	ctx, cancel := context.WithCancel(context.Background())
    53  	cancel()
    54  	mu.Lock()
    55  	if got, want := cond.Wait(ctx), context.Canceled; got != want {
    56  		t.Errorf("got %v, want %v", got, want)
    57  	}
    58  }