balancing locking works

This commit is contained in:
Radu Ioan Fericean
2012-01-25 14:25:45 +02:00
parent e5b2be3b8c
commit c29a50691b
2 changed files with 18 additions and 8 deletions

View File

@@ -5,7 +5,7 @@ import (
"log"
"net/http"
"net/rpc"
//"time"
"time"
"errors"
)
@@ -34,9 +34,9 @@ func callRater() {
}
func testCallRater(){
for i:= 0; i<10; i++ {
for {
go callRater()
//time.Sleep(1 * time.Second)
time.Sleep(1 * time.Second)
}
}

View File

@@ -5,18 +5,22 @@ import (
"log"
"net/rpc"
"time"
"sync"
)
type RaterList struct {
Clients map[string]*rpc.Client
Balancer chan *rpc.Client
balancer_mutex sync.Mutex
}
func NewRaterList() *RaterList {
return &RaterList{
r:= &RaterList{
Clients: make(map[string]*rpc.Client),
Balancer: make(chan *rpc.Client),
}
r.startBalance()
return r
}
func (rl *RaterList) RegisterRater(clientAddress string, replay *byte) error {
@@ -27,7 +31,7 @@ func (rl *RaterList) RegisterRater(clientAddress string, replay *byte) error {
}
rl.Clients[clientAddress] = client
log.Print(fmt.Sprintf("Server %v registered succesfully", clientAddress))
rl.startBalance()
rl.balancer_mutex.Unlock()
return nil
}
@@ -35,17 +39,23 @@ func (rl *RaterList) UnRegisterRater(clientAddress string, replay *byte) error {
client := rl.Clients[clientAddress]
client.Close()
delete(rl.Clients, clientAddress)
log.Print(fmt.Sprintf("Server %v unregistered succesfully", clientAddress))
log.Print(fmt.Sprintf("Server %v unregistered succesfully", clientAddress))
return nil
}
func (rl *RaterList) startBalance() {
rl.balancer_mutex.Lock()
go func(){
for {
for {
rl.balancer_mutex.Lock()
log.Print("balancing")
for addr, client := range rl.Clients {
log.Printf("using server %s:", addr)
rl.Balancer <- client
rl.Balancer <- client
}
if len(rl.Clients) != 0 {
rl.balancer_mutex.Unlock()
}
}
}()
}