go.etcd.io/etcd@v3.3.27+incompatible/clientv3/concurrency/example_mutex_test.go (about)

     1  // Copyright 2017 The etcd Authors
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package concurrency_test
    16  
    17  import (
    18  	"context"
    19  	"fmt"
    20  	"log"
    21  
    22  	"github.com/coreos/etcd/clientv3"
    23  	"github.com/coreos/etcd/clientv3/concurrency"
    24  )
    25  
    26  func ExampleMutex_Lock() {
    27  	cli, err := clientv3.New(clientv3.Config{Endpoints: endpoints})
    28  	if err != nil {
    29  		log.Fatal(err)
    30  	}
    31  	defer cli.Close()
    32  
    33  	// create two separate sessions for lock competition
    34  	s1, err := concurrency.NewSession(cli)
    35  	if err != nil {
    36  		log.Fatal(err)
    37  	}
    38  	defer s1.Close()
    39  	m1 := concurrency.NewMutex(s1, "/my-lock/")
    40  
    41  	s2, err := concurrency.NewSession(cli)
    42  	if err != nil {
    43  		log.Fatal(err)
    44  	}
    45  	defer s2.Close()
    46  	m2 := concurrency.NewMutex(s2, "/my-lock/")
    47  
    48  	// acquire lock for s1
    49  	if err := m1.Lock(context.TODO()); err != nil {
    50  		log.Fatal(err)
    51  	}
    52  	fmt.Println("acquired lock for s1")
    53  
    54  	m2Locked := make(chan struct{})
    55  	go func() {
    56  		defer close(m2Locked)
    57  		// wait until s1 is locks /my-lock/
    58  		if err := m2.Lock(context.TODO()); err != nil {
    59  			log.Fatal(err)
    60  		}
    61  	}()
    62  
    63  	if err := m1.Unlock(context.TODO()); err != nil {
    64  		log.Fatal(err)
    65  	}
    66  	fmt.Println("released lock for s1")
    67  
    68  	<-m2Locked
    69  	fmt.Println("acquired lock for s2")
    70  
    71  	// Output:
    72  	// acquired lock for s1
    73  	// released lock for s1
    74  	// acquired lock for s2
    75  }