6.5840 Lab-Key/Value Server 思路

6.824 Lab 2: Key/Value Server

在本实验中,需要构建一个键/值服务器, 以确保每个操作在网络故障 的情况下都只执行一次, 并且操作是线性化的。

网络故障

示例代码

Go 复制代码
type Clerk struct {
	server   *labrpc.ClientEnd
	workerId int64
	seq      int64
}
Go 复制代码
func (ck *Clerk) PutAppend(key string, value string, op string) string {
	reply := new(PutAppendReply)
	for !reply.Ok {
		ck.server.Call("KVServer."+op, &PutAppendArgs{key, value, ck.workerId, ck.seq}, reply)
	}
	ck.seq++
	v := reply.Value
	reply.Ok = false
	return v
}
Go 复制代码
type KVServer struct {
	mu sync.RWMutex

	m      map[string]string
	seqSet map[string]string
}
Go 复制代码
func (kv *KVServer) Append(args *PutAppendArgs, reply *PutAppendReply) {
	kv.mu.Lock()
	defer kv.mu.Unlock()
	
	key := strconv.Itoa(int(args.WorkerId)) + strconv.Itoa(int(args.Seq))
	//检查是不是执行过
	if v, ok := kv.seqSet[key]; ok {
		reply.Ok = true
		reply.Value = v
		return
	}
	//删除上一次的缓存
	delete(kv.seqSet, strconv.Itoa(int(args.WorkerId))+strconv.Itoa(int(args.Seq-1)))
	//执行Append
	s := kv.m[args.Key]
	kv.seqSet[key] = s
	kv.m[args.Key] = s + args.Value
	reply.Value = s
	reply.Ok = true
}

tips

  • 测试文件运行在linux下比windows快不少,建议在linux测试
相关推荐
Oneslide8 小时前
Ubuntu 26.04 完整安装 Fcitx5 中文拼音输入法指南(适配默认Wayland)
后端
huangdong_8 小时前
电商平台图片URL原图转换技术深度解析:从缩略图到高清原图的完整方案
java·后端·spring
掘金码甲哥9 小时前
3min手搓一个帮助文档站,很合理吧!
后端
ServBay13 小时前
别再用初级写法写Rust了,8个写法你值得拥有
后端·rust
jingling55513 小时前
go | 环境安装和快速入门
开发语言·后端·golang
Darren24513 小时前
流程步骤模板 - @StepStatus 注解方案
后端
小闹54914 小时前
Claude Code 给自己接了一部飞书,从此不用守在工位等它
后端·claude
浮游本尊14 小时前
Java学习第41天 - 复杂查询、多表关联、索引优化与慢 SQL 调优
后端
llz_11214 小时前
web-第五次课后作业
前端·后端·http