线程安全的 Map

我们知道在 Go 语言里面 map 是非线程安全的,详细的 atomic_maps。但是我们在平常的业务中经常需要用到线程安全的 map,特别是在 goroutine 的情况下,所以 beego 内置了一个简单的线程安全的 map:

  1. bm := NewBeeMap()
  2. if !bm.Set("astaxie", 1) {
  3. t.Error("set Error")
  4. }
  5. if !bm.Check("astaxie") {
  6. t.Error("check err")
  7. }
  8. if v := bm.Get("astaxie"); v.(int) != 1 {
  9. t.Error("get err")
  10. }
  11. bm.Delete("astaxie")
  12. if bm.Check("astaxie") {
  13. t.Error("delete err")
  14. }

上面演示了如何使用线程安全的 Map,主要的接口有:

  • Get(k interface{}) interface{}
  • Set(k interface{}, v interface{}) bool
  • Check(k interface{}) bool
  • Delete(k interface{})