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测试
相关推荐
红尘散仙5 小时前
我把终端小说阅读器接上了 AI Agent:TRNovel 现在能用 skill 生成书源了
人工智能·后端·rust
卷毛的技术笔记6 小时前
告别硬编码!Spring AI Alibaba 实现 AI Agent 智能工具调用(Tool Calling)
java·人工智能·后端·python·spring·ai编程
会编程的土豆6 小时前
Go 语言反射(Reflection)详解
开发语言·后端·golang
喵个咪7 小时前
GoWind Toolkit Go后端代码生成 完整全流程实战
后端·go·orm
basketball6167 小时前
Go 语言从入门到进阶:4. 数组和MAP使用方法总结
开发语言·后端·golang
qq_2518364577 小时前
SpringBoot+Vue 共享电池柜管理系统 完整实现 前后端分离项目实战 完整代码
vue.js·spring boot·后端
zhangxingchao8 小时前
AI 大模型核心六:量化、Workflow 与 Agent、多轮 RAG
前端·人工智能·后端
IT_陈寒9 小时前
Vite打包时遇到的坑,原来问题出在这里
前端·人工智能·后端
ayqy贾杰10 小时前
基层管理的三板斧,在AI时代行不通了
前端·后端·团队管理
Apifox10 小时前
Apifox 5 月更新|Postman 导入优化、Runner 支持非 root 运行、请求代码自动带鉴权
前端·后端·安全