test.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. clientv3 "go.etcd.io/etcd/client/v3"
  6. "go.etcd.io/etcd/client/v3/concurrency"
  7. "time"
  8. )
  9. func main() {
  10. cli, err := clientv3.New(clientv3.Config{
  11. Endpoints: []string{"106.54.33.152:2379"},
  12. DialTimeout: 5 * time.Second,
  13. })
  14. if err != nil {
  15. panic(err)
  16. }
  17. defer cli.Close()
  18. for i := 0; i < 10; i++ {
  19. go func(i int) {
  20. m, err := NewPciLock(cli)
  21. if err != nil {
  22. fmt.Printf("Error creating")
  23. }
  24. m.IsOwner()
  25. err = m.Lock(context.Background())
  26. if err != nil {
  27. fmt.Printf("Failed to lock: %v\n", err)
  28. return
  29. }
  30. if i == 1 {
  31. time.Sleep(time.Second * 10)
  32. }
  33. fmt.Println(i)
  34. err = m.Unlock(context.Background())
  35. if err != nil {
  36. fmt.Printf("Failed to Unlock: %v\n", err)
  37. return
  38. }
  39. }(i)
  40. }
  41. time.Sleep(time.Second * 15)
  42. }
  43. func NewPciLock(etcd *clientv3.Client) (*concurrency.Mutex, error) {
  44. session, err := concurrency.NewSession(etcd, concurrency.WithTTL(5))
  45. if err != nil {
  46. return nil, err
  47. }
  48. m := concurrency.NewMutex(session, "hstack/server/pciLock")
  49. return m, nil
  50. }