Created
March 1, 2018 16:12
-
-
Save antsmartian/2a58e32fa766136593c1669e44daca65 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"sync" | |
) | |
type DB struct { | |
mu sync.RWMutex | |
data map[string]string | |
} | |
func Open(path string) (*DB,error) { | |
db := &DB{ | |
data : make(map[string]string), | |
} | |
return db, nil | |
} | |
type Tx struct { | |
db *DB | |
writable bool | |
funcd bool | |
} | |
func (tx *Tx) lock() { | |
if tx.writable { | |
tx.db.mu.Lock() | |
} else { | |
tx.db.mu.RLock() | |
} | |
} | |
func (tx *Tx) unlock() { | |
if tx.writable { | |
tx.db.mu.Unlock() | |
} else { | |
tx.db.mu.RUnlock() | |
} | |
} | |
func (tx *Tx) Set(key, value string) { | |
fmt.Println("Setting value... " , key , value) | |
tx.db.data[key] = value | |
} | |
func (tx *Tx) Get(key string) string { | |
return tx.db.data[key] | |
} | |
func (db * DB) View(fn func (tx *Tx) error) error { | |
return db.managed(false, fn) | |
} | |
func (db * DB) Update(fn func (tx *Tx) error) error { | |
return db.managed(true, fn) | |
} | |
func (db *DB) Begin(writable bool) (*Tx,error) { | |
tx := &Tx { | |
db : db, | |
writable: writable, | |
} | |
tx.lock() | |
return tx,nil | |
} | |
func (db *DB) managed(writable bool, fn func(tx *Tx) error) (err error) { | |
var tx *Tx | |
tx, err = db.Begin(writable) | |
if err != nil { | |
return | |
} | |
defer func() { | |
if writable { | |
fmt.Println("Write Unlocking...") | |
tx.unlock() | |
} else { | |
fmt.Println("Read Unlocking...") | |
tx.unlock() | |
} | |
}() | |
tx.funcd = true | |
defer func() { | |
tx.funcd = false | |
}() | |
err = fn(tx) | |
return | |
} | |
func main() { | |
fmt.Print("hello") | |
db,_ := Open("data.db") | |
go db.Update(func(tx *Tx) error { | |
tx.Set("mykey", "myvalue") | |
return nil | |
}) | |
go db.View(func(tx *Tx) error { | |
fmt.Println(tx.Get("mykey")) | |
return nil | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment