1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
|
type Clerk struct {
server *labrpc.ClientEnd
clientID int64
requestID int64
mu sync.Mutex
}
func nrand() int64 {
max := big.NewInt(int64(1) << 62)
bigx, _ := rand.Int(rand.Reader, max)
x := bigx.Int64()
return x
}
func MakeClerk(server *labrpc.ClientEnd) *Clerk {
ck := &Clerk{
clientID: nrand(),
requestID: 0,
}
ck.server = server
return ck
}
func (ck *Clerk) Get(key string) string {
args := GetArgs{Key: key}
var reply GetReply
for {
ok := ck.server.Call("KVServer.Get", &args, &reply)
if ok {
return reply.Value
} else {
time.Sleep(100 * time.Millisecond)
}
}
}
func (ck *Clerk) PutAppend(key string, value string, op string) string {
args := PutAppendArgs{
ClientId: ck.clientID,
Key: key,
Value: value,
RequestId: ck.requestID,
}
var reply PutAppendReply
for {
ok := ck.server.Call("KVServer."+op, &args, &reply)
if ok {
ck.mu.Lock()
ck.requestID++
ck.mu.Unlock()
return reply.Value
} else {
time.Sleep(100 * time.Millisecond)
}
}
}
func (ck *Clerk) Put(key string, value string) {
ck.PutAppend(key, value, "Put")
}
func (ck *Clerk) Append(key string, value string) string {
return ck.PutAppend(key, value, "Append")
}
|