我想在 Go 中编写一个小型内存数据库。读取和写入请求将通过通道传递并由数据库引擎处理,以确保访问正确完成。
第一个想法是模仿RWMutex的行为。只有它会使用更惯用的围棋风格。
这是我想做的一个小玩具(虽然相当长)的例子。
package main
import (
"log"
"math/rand"
"time"
)
var source *rand.Rand
type ReqType int
const (
READ = iota
WRITE
)
type DbRequest struct {
Type int // request type
RespC chan *DbResponse // channel for request response
// content here
}
type DbResponse struct {
// response here
}
type Db struct {
// DB here
}
func randomWait() {
time.Sleep(time.Duration(source.Intn(1000)) * time.Millisecond)
}
func (d *Db) readsHandler(in <-chan *DbRequest) {
for r := range in {
id := source.Intn(4000000)
log.Println("read ", id, " starts")
randomWait()
log.Println("read ", id, " ends")
r.RespC <- &DbResponse{}
}
}
func (d *Db) writesHandler(r *DbRequest) *DbResponse {
id := source.Intn(4000000)
log.Println("write ", id, " starts")
randomWait()
log.Println("write ", id, " ends")
return &DbResponse{}
}
func (d *Db) Start(nReaders int) chan *DbRequest {
in := make(chan *DbRequest, 100)
reads := make(chan *DbRequest, nReaders)
// launch readers
for k := 0; k < nReaders; k++ {
go d.readsHandler(reads)
}
go func() {
for r := range in {
switch r.Type {
case READ:
reads <- r
case WRITE:
// here we should wait for all reads to
// be over (how ??)
r.RespC <- d.writesHandler(r)
// here writesHandler is blocking,
// this ensures that no additional
// read is added in the reads channel
// before the write is finished
}
}
}()
return in
}
func main() {
seed := time.Now().Unix()
source = rand.New(rand.NewSource(seed))
blackhole := make(chan *DbResponse, 100)
d := Db{}
rc := d.Start(4)
wc := time.After(3 * time.Second)
go func() {
for {
<-blackhole
}
}()
for {
select {
case <-wc:
return
default:
if source.Intn(2) == 0 {
rc <- &DbRequest{READ, blackhole}
} else {
rc <- &DbRequest{WRITE, blackhole}
}
}
}
}
当然,这个例子显示了读/写冲突。
我觉得我正在尝试做一些有点邪恶的事情:使用旨在避免它的结构共享内存......此时,一个明显的解决方案是在两种类型的请求处理周围添加 RWMutex 锁,但也许有一个仅使用 goroutine 和通道的巧妙解决方案。