353 字
2 分钟
MIT 6.5840(原 6.824) 通关笔记 Lab2 Key/Value Server

这个Lab是Spring 2024的新Lab,难度十分低。

Key/value server with no network failures#

太简单了以至于没什么好记录的,no network failures意味着实现线性化只需要加锁就可以了。

Key/value server with dropped messages#

实验要求是server再次收到已完成过的请求时丢弃重复请求不处理,只需要用map记录下处理过且未经客户端确认的请求,在收到客户端ACK后清理即可。

内存释放#

起初是使用了map存储nrand()生成的操作id和对应的append操作发生前的结果字符串,但是这样没法通过memory use many appends这个case。然后注意到其实append操作不会修改之前的存在结果,所以历史map可以改为存储append前的value字符串长度,这样就可以将string改为int以此节省内存。

server代码#

type KVServer struct {
	mu sync.Mutex
	// Your definitions here.
	pairs   map[string]string
	history map[int64]int
}

func (kv *KVServer) Get(args *GetArgs, reply *GetReply) {
	// Your code here.
	kv.mu.Lock()
	defer kv.mu.Unlock()

	reply.Value = kv.pairs[args.Key]

}

func (kv *KVServer) Put(args *PutAppendArgs, reply *PutAppendReply) {
	// Your code here.

	kv.mu.Lock()
	defer kv.mu.Unlock()
	kv.pairs[args.Key] = args.Value
	delete(kv.history, args.ID)
}

func (kv *KVServer) Append(args *PutAppendArgs, reply *PutAppendReply) {
	// Your code here.
	kv.mu.Lock()
	defer kv.mu.Unlock()
	if args.Report {
		delete(kv.history, args.ID)
		return
	}
	if val, ok := kv.history[args.ID]; ok {
		reply.Value = kv.pairs[args.Key][:val]
		return
	}
	reply.Value = kv.pairs[args.Key]
	kv.history[args.ID] = len(reply.Value)
	kv.pairs[args.Key] += args.Value
}

func StartKVServer() *KVServer {
	kv := new(KVServer)

	// You may need initialization code here.
	kv.pairs = make(map[string]string)
	kv.history = make(map[int64]int)

	return kv
}
MIT 6.5840(原 6.824) 通关笔记 Lab2 Key/Value Server
https://yomi.moe/posts/mit65840-2/
作者
藍々
发布于
2024-11-16
许可协议
CC BY-NC-SA 4.0