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测试
相关推荐
GreenTea1 天前
深度解读 Anthropic 多智能体报告:更强的模型 ≠ 更好的协调
前端·后端·算法
风流 少年1 天前
Spring AI 2.0:Memory
java·后端·spring
万少1 天前
给 DeepSeek Harness 装个"应用商店":一条命令,595 个插件随你逛
前端·javascript·后端
IT_陈寒1 天前
Python的GIL让我多写了500行代码
前端·人工智能·后端
IT爱学堂1 天前
精讲软件设计师(软考中级)一站式通关课_实战课程_慕课网
后端
战天战地站房顶1 天前
在 Windows Docker 中部署 PostgreSQL 17 + pgvector 完整指南
后端
卷无止境1 天前
FastAPI Guard 全解析,从概念到工程落地的实战指南
后端·python
卷无止境1 天前
FastAPI Users 全面解析:概念、原理与工程实战
后端·python
程序员爱钓鱼1 天前
Go switch 详解
后端·面试·go
程序员爱钓鱼1 天前
Rust Struct结构体详解:定义自己的复杂数据类型
后端·面试·rust