Created
March 23, 2017 06:35
-
-
Save codemartial/ab59eb56543985202a1f55c1537e5e00 to your computer and use it in GitHub Desktop.
etcd Mutex experimentation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"context" | |
"fmt" | |
etcc "github.com/coreos/etcd/clientv3" | |
etcsync "github.com/coreos/etcd/clientv3/concurrency" | |
"time" | |
) | |
func main() { | |
etcd, err := etcc.New(etcc.Config{ | |
Endpoints: []string{"localhost:2379"}, | |
}) | |
if err != nil { | |
fmt.Println(err) | |
return | |
} | |
defer etcd.Close() | |
ec := make(chan int) | |
lc := make(chan int) | |
for i := 0; i < 10; i++ { | |
go contend(i, etcd, ec, lc) | |
} | |
var locked, errored int | |
for i := 0; i < 10; i++ { | |
select { | |
case <-lc: | |
locked++ | |
case <-ec: | |
errored++ | |
} | |
} | |
fmt.Println("locked: ", locked, " errored:", errored) | |
} | |
func contend(i int, etcd *etcc.Client, ec, lc chan int) { | |
var sigchan chan int | |
var ctx context.Context | |
var mu *etcsync.Mutex | |
var s *etcsync.Session | |
var cancel func() | |
defer func() { | |
time.AfterFunc(200*time.Millisecond, cancel) | |
if mu != nil { | |
mu.Unlock(ctx) | |
} | |
if s != nil { | |
s.Close() | |
} | |
if sigchan != nil { | |
sigchan <- 1 | |
} | |
}() | |
ctx, cancel = context.WithDeadline(context.Background(), time.Now().Add(200*time.Millisecond)) | |
s, err := etcsync.NewSession(etcd, etcsync.WithContext(ctx)) | |
if err != nil { | |
fmt.Println(i, "session init failed") | |
return | |
} | |
mu = etcsync.NewMutex(s, "/testmutex") | |
if err := mu.Lock(ctx); err != nil { | |
sigchan = ec | |
return | |
} | |
time.Sleep(100 * time.Millisecond) | |
sigchan = lc | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment