Browse files

db: fix data race in session update

Fix #284.
  • Loading branch information...
1 parent 6aa3990 commit d2032bafc6e8fdeecaf49f5b78ada4d3a34f8a8f @fsouza fsouza committed Jan 22, 2013
Showing with 44 additions and 1 deletion.
  1. +43 −0 db/race_test.go
  2. +1 −1 db/storage.go
View
43 db/race_test.go
@@ -0,0 +1,43 @@
+// Copyright 2013 tsuru authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// +build race
+
+package db
+
+import (
+ . "launchpad.net/gocheck"
+ "sync"
+ "time"
+)
+
+func (s *S) TestOpenIsThreadSafe(c *C) {
+ storage, err := Open("127.0.0.1:27017", "tsuru_db_race_tests")
+ c.Assert(err, IsNil)
+ defer storage.session.Close()
+ sess := conn["127.0.0.1:27017"]
+ sess.used = time.Now().Add(-1 * time.Hour)
+ conn["127.0.0.1:27017"] = sess
+ var wg sync.WaitGroup
+ wg.Add(3)
+ go func() {
+ st1, err := Open("127.0.0.1:27017", "tsuru_db_race_tests_2")
+ c.Check(err, IsNil)
+ c.Check(st1.session, Equals, storage.session)
+ wg.Done()
+ }()
+ go func() {
+ st2, err := Open("127.0.0.1:27017", "tsuru_db_race_tests_3")
+ c.Check(err, IsNil)
+ c.Check(st2.session, Equals, storage.session)
+ wg.Done()
+ }()
+ go func() {
+ st3, err := Open("127.0.0.1:27017", "tsuru_db_race_tests_4")
+ c.Check(err, IsNil)
+ c.Check(st3.session, Equals, storage.session)
+ wg.Done()
+ }()
+ wg.Wait()
+}
View
2 db/storage.go
@@ -66,8 +66,8 @@ func Open(addr, dbname string) (storage *Storage, err error) {
if session, ok := conn[addr]; ok {
mut.RUnlock()
if err = session.s.Ping(); err == nil {
- session.used = time.Now()
mut.Lock()
+ session.used = time.Now()
conn[addr] = session
mut.Unlock()
return &Storage{session.s, dbname}, nil

0 comments on commit d2032ba

Please sign in to comment.