Skip to content

Instantly share code, notes, and snippets.

@1lann
Last active June 27, 2017 06:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 1lann/30cc4c981449fa13db7e8d9943dfc2e6 to your computer and use it in GitHub Desktop.
Save 1lann/30cc4c981449fa13db7e8d9943dfc2e6 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"sync"
"github.com/dgraph-io/badger/badger"
)
func main() {
opts := badger.DefaultOptions
opts.Dir = "./data"
opts.ValueDir = "./data"
kv, err := badger.NewKV(&opts)
if err != nil {
panic(err)
}
defer kv.Close()
wg := new(sync.WaitGroup)
wg.Add(2)
go write(kv, wg, 1)
go write(kv, wg, 2)
wg.Wait()
var item badger.KVItem
err = kv.Get([]byte("test"), &item)
if err != nil {
panic(err)
}
fmt.Println("Final value:", item.Value())
}
func write(kv *badger.KV, wg *sync.WaitGroup, value byte) {
defer wg.Done()
var item badger.KVItem
err := kv.Get([]byte("test"), &item)
if err != nil {
panic(err)
}
fmt.Println("Item's value:", item.Value())
newValue := make([]byte, len(item.Value())+1)
copy(newValue, item.Value())
newValue[len(newValue)-1] = value
fmt.Println("New value:", newValue)
fmt.Println("Write result:", kv.CompareAndSet([]byte("test"), newValue, item.Counter()))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment