Skip to content

Instantly share code, notes, and snippets.

@floridoo
Created January 29, 2016 10:16
Show Gist options
  • Save floridoo/2621afccc55130a5334c to your computer and use it in GitHub Desktop.
Save floridoo/2621afccc55130a5334c to your computer and use it in GitHub Desktop.
go-memdb race condition
package main
import (
"fmt"
"time"
memdb "github.com/hashicorp/go-memdb"
)
func main() {
// Create a sample struct
type Person struct {
Email string
Name string
Age int
}
// Create the DB schema
schema := &memdb.DBSchema{
Tables: map[string]*memdb.TableSchema{
"person": &memdb.TableSchema{
Name: "person",
Indexes: map[string]*memdb.IndexSchema{
"id": &memdb.IndexSchema{
Name: "id",
Unique: true,
Indexer: &memdb.StringFieldIndex{Field: "Email"},
},
},
},
},
}
// Create a new data base
db, err := memdb.NewMemDB(schema)
if err != nil {
panic(err)
}
go func() {
counter := 0
for {
counter++
// Create a write transaction
txn := db.Txn(true)
// Insert a new person
p := &Person{"joe@aol.com", "Joe", counter}
if err := txn.Insert("person", p); err != nil {
panic(err)
}
// Commit the transaction
txn.Commit()
time.Sleep(1 * time.Second)
}
}()
for {
// Create read-only transaction
txn := db.Txn(false)
defer txn.Abort()
// Lookup by email
raw, err := txn.First("person", "id", "joe@aol.com")
if err != nil {
panic(err)
}
if raw != nil {
// Say hi!
fmt.Printf("Hello %s %d!\n", raw.(*Person).Name, raw.(*Person).Age)
}
time.Sleep(1 * time.Second)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment