example_mutex_test.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. package concurrency_test
  15. import (
  16. "context"
  17. "fmt"
  18. "log"
  19. "go.etcd.io/etcd/clientv3"
  20. "go.etcd.io/etcd/clientv3/concurrency"
  21. )
  22. func ExampleMutex_Lock() {
  23. cli, err := clientv3.New(clientv3.Config{Endpoints: endpoints})
  24. if err != nil {
  25. log.Fatal(err)
  26. }
  27. defer cli.Close()
  28. // create two separate sessions for lock competition
  29. s1, err := concurrency.NewSession(cli)
  30. if err != nil {
  31. log.Fatal(err)
  32. }
  33. defer s1.Close()
  34. m1 := concurrency.NewMutex(s1, "/my-lock/")
  35. s2, err := concurrency.NewSession(cli)
  36. if err != nil {
  37. log.Fatal(err)
  38. }
  39. defer s2.Close()
  40. m2 := concurrency.NewMutex(s2, "/my-lock/")
  41. // acquire lock for s1
  42. if err := m1.Lock(context.TODO()); err != nil {
  43. log.Fatal(err)
  44. }
  45. fmt.Println("acquired lock for s1")
  46. m2Locked := make(chan struct{})
  47. go func() {
  48. defer close(m2Locked)
  49. // wait until s1 is locks /my-lock/
  50. if err := m2.Lock(context.TODO()); err != nil {
  51. log.Fatal(err)
  52. }
  53. }()
  54. if err := m1.Unlock(context.TODO()); err != nil {
  55. log.Fatal(err)
  56. }
  57. fmt.Println("released lock for s1")
  58. <-m2Locked
  59. fmt.Println("acquired lock for s2")
  60. // Output:
  61. // acquired lock for s1
  62. // released lock for s1
  63. // acquired lock for s2
  64. }