Skip to content

Commit

Permalink
fix: Panic when closing DB while other goroutines doing reads
Browse files Browse the repository at this point in the history
Signed-off-by: fatelei <[email protected]>
  • Loading branch information
fatelei committed Aug 4, 2023
1 parent c2e611a commit 4a1abab
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
2 changes: 1 addition & 1 deletion db.go
Original file line number Diff line number Diff line change
Expand Up @@ -546,6 +546,7 @@ func (db *DB) close() (err error) {
db.opt.Infof("Lifetime L0 stalled for: %s\n", time.Duration(db.lc.l0stallsMs.Load()))

db.blockWrites.Store(1)
db.isClosed.Store(1)

if !db.opt.InMemory {
// Stop value GC first.
Expand Down Expand Up @@ -631,7 +632,6 @@ func (db *DB) close() (err error) {
db.blockCache.Close()
db.indexCache.Close()

db.isClosed.Store(1)
db.threshold.close()

if db.opt.InMemory {
Expand Down
34 changes: 34 additions & 0 deletions db_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2635,3 +2635,37 @@ func TestCompactL0OnClose(t *testing.T) {
}
})
}

func TestCloseDBWhileReading(t *testing.T) {
dir := t.TempDir()
db, err := Open(DefaultOptions(dir))
require.NoError(t, err)

key := []byte("key")
err = db.Update(func(txn *Txn) error {
return txn.Set(key, []byte("value"))
})
require.NoError(t, err)

var wg sync.WaitGroup
for i := 0; i < 10; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for {
err := db.View(func(txn *Txn) error {
_, err := txn.Get(key)
return err
})
if err != nil {
require.Contains(t, err.Error(), "DB Closed")
break
}
}
}()
}

time.Sleep(time.Second)
require.NoError(t, db.Close())
wg.Wait()
}

0 comments on commit 4a1abab

Please sign in to comment.