【发布时间】:2015-05-20 02:01:25
【问题描述】:
我使用this 作为并发映射,缓冲通道作为线程安全的映射值(作为队列工作),当测试使用 10 个 goroutines 时,从通道获得的值与发送的不同,有什么建议吗?
package main
import "fmt"
import "github.com/streamrail/concurrent-map"
func main() {
testmap := cmap.New()
fmt.Println("SyncMapNew: ", TestInParallel(&testmap, 10))
}
func TestInParallel(g *cmap.ConcurrentMap, n int) time.Duration {
start := time.Now()
var wait sync.WaitGroup
for i := 0; i < n; i++ {
wait.Add(1)
go func() {
TheTest(g, rand.New(rand.NewSource(int64(i*500))))
wait.Done()
}()
}
wait.Wait()
return time.Now().Sub(start)
}
func TheTest(g *cmap.ConcurrentMap, rnd *rand.Rand) time.Duration {
start := time.Now()
var key string
var value time.Time
for i := 0; i < 10000; i++ {
key = strconv.Itoa(int(rnd.Int31n(50000)))
if g.Has(key) == false {
g.Set(key, make(chan time.Time, 100))
}
tchan, _ := g.Get(key)
castchan := tchan.(chan time.Time)
value = time.Now()
castchan <- value
got := <-castchan
g.Set(key, castchan)
if value != got {
panic(fmt.Sprintf("ERROR: expected %v, got %v", value, got))
}
}
return time.Now().Sub(start)
}
更新我误解了业务逻辑,代码应该是这样的
key = strconv.Itoa(int(rnd.Int31n(500)))
tchan, _ := g.GetSet(key, make(chan time.Time, 100))
castchan := tchan.(chan time.Time)
value = time.Now()
if len(castchan) >= 99 {
<-castchan//do somthing here
}
castchan <- value
g.Set(key, castchan)
【问题讨论】:
-
鉴于您正在使用的“concurent-map”包中的缺陷(David Budworth's answer 中提到了一些,还有更多),并且您可以轻松添加
sync.Mutex自己锁定你真正需要的东西(这通常比单独的地图访问多一点)我认为没有理由使用这个包。
标签: dictionary concurrency go