Created
January 29, 2016 10:16
-
-
Save floridoo/2621afccc55130a5334c to your computer and use it in GitHub Desktop.
go-memdb race condition
This file contains 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 ( | |
"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