1
0
mirror of https://github.com/chai2010/advanced-go-programming-book.git synced 2025-05-29 08:12:21 +00:00
This commit is contained in:
Xargin 2018-08-03 13:55:19 +08:00
parent b7aeb00f6a
commit 9b6a55d791

View File

@ -226,48 +226,48 @@ unlock success!
package main package main
import ( import (
"fmt" "fmt"
"log" "log"
"os" "os"
"time" "time"
"github.com/nladuo/go-zk-lock" "github.com/nladuo/go-zk-lock"
) )
var ( var (
hosts []string = []string{"127.0.0.1:2181"} // the zookeeper hosts hosts []string = []string{"127.0.0.1:2181"} // the zookeeper hosts
basePath string = "/locker" //the application znode path basePath string = "/locker" //the application znode path
lockerTimeout time.Duration = 5 * time.Second // the maximum time for a locker waiting lockerTimeout time.Duration = 5 * time.Second // the maximum time for a locker waiting
zkTimeOut time.Duration = 20 * time.Second // the zk connection timeout zkTimeOut time.Duration = 20 * time.Second // the zk connection timeout
) )
func main() { func main() {
end := make(chan byte) end := make(chan byte)
err := DLocker.EstablishZkConn(hosts, zkTimeOut) err := DLocker.EstablishZkConn(hosts, zkTimeOut)
defer DLocker.CloseZkConn() defer DLocker.CloseZkConn()
if err != nil { if err != nil {
fmt.Println(err) fmt.Println(err)
os.Exit(1) os.Exit(1)
} }
//concurrent test lock and unlock //concurrent test lock and unlock
for i := 0; i < 100; i++ { for i := 0; i < 100; i++ {
go run(i) go run(i)
} }
<-end <-end
} }
func run(i int) { func run(i int) {
locker := DLocker.NewLocker(basePath, lockerTimeout) locker := DLocker.NewLocker(basePath, lockerTimeout)
for { for {
locker.Lock() // like mutex.Lock() locker.Lock() // like mutex.Lock()
fmt.Println("gorountine", i, ": get lock") fmt.Println("gorountine", i, ": get lock")
//do something of which time not excceed lockerTimeout //do something of which time not excceed lockerTimeout
fmt.Println("gorountine", i, ": unlock") fmt.Println("gorountine", i, ": unlock")
if !locker.Unlock() { // like mutex.Unlock(), return false when zookeeper connection error or locker timeout if !locker.Unlock() { // like mutex.Unlock(), return false when zookeeper connection error or locker timeout
log.Println("gorountine", i, ": unlock failed") log.Println("gorountine", i, ": unlock failed")
} }
} }
} }
``` ```