mirror of
https://github.com/astaxie/beego.git
synced 2024-11-22 18:00:55 +00:00
Merge pull request #3635 from edwardhey/develop
Incr和Decr应该改成排它锁,否则在并发的时候会出现非期望的结果值
This commit is contained in:
commit
585df01899
23
cache/cache_test.go
vendored
23
cache/cache_test.go
vendored
@ -16,10 +16,33 @@ package cache
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"os"
|
"os"
|
||||||
|
"sync"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
func TestCacheIncr(t *testing.T) {
|
||||||
|
bm, err := NewCache("memory", `{"interval":20}`)
|
||||||
|
if err != nil {
|
||||||
|
t.Error("init err")
|
||||||
|
}
|
||||||
|
//timeoutDuration := 10 * time.Second
|
||||||
|
|
||||||
|
bm.Put("edwardhey", 0, time.Second*20)
|
||||||
|
wg := sync.WaitGroup{}
|
||||||
|
wg.Add(10)
|
||||||
|
for i := 0; i < 10; i++ {
|
||||||
|
go func() {
|
||||||
|
defer wg.Done()
|
||||||
|
bm.Incr("edwardhey")
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
wg.Wait()
|
||||||
|
if bm.Get("edwardhey").(int) != 10 {
|
||||||
|
t.Error("Incr err")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestCache(t *testing.T) {
|
func TestCache(t *testing.T) {
|
||||||
bm, err := NewCache("memory", `{"interval":20}`)
|
bm, err := NewCache("memory", `{"interval":20}`)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
8
cache/memory.go
vendored
8
cache/memory.go
vendored
@ -110,8 +110,8 @@ func (bc *MemoryCache) Delete(name string) error {
|
|||||||
// Incr increase cache counter in memory.
|
// Incr increase cache counter in memory.
|
||||||
// it supports int,int32,int64,uint,uint32,uint64.
|
// it supports int,int32,int64,uint,uint32,uint64.
|
||||||
func (bc *MemoryCache) Incr(key string) error {
|
func (bc *MemoryCache) Incr(key string) error {
|
||||||
bc.RLock()
|
bc.Lock()
|
||||||
defer bc.RUnlock()
|
defer bc.Unlock()
|
||||||
itm, ok := bc.items[key]
|
itm, ok := bc.items[key]
|
||||||
if !ok {
|
if !ok {
|
||||||
return errors.New("key not exist")
|
return errors.New("key not exist")
|
||||||
@ -137,8 +137,8 @@ func (bc *MemoryCache) Incr(key string) error {
|
|||||||
|
|
||||||
// Decr decrease counter in memory.
|
// Decr decrease counter in memory.
|
||||||
func (bc *MemoryCache) Decr(key string) error {
|
func (bc *MemoryCache) Decr(key string) error {
|
||||||
bc.RLock()
|
bc.Lock()
|
||||||
defer bc.RUnlock()
|
defer bc.Unlock()
|
||||||
itm, ok := bc.items[key]
|
itm, ok := bc.items[key]
|
||||||
if !ok {
|
if !ok {
|
||||||
return errors.New("key not exist")
|
return errors.New("key not exist")
|
||||||
|
Loading…
Reference in New Issue
Block a user