github.com/qiuhoude/go-web@v0.0.0-20220223060959-ab545e78f20d/prepare/14_concurrent/happensb/custommap.go (about)

     1  package main
     2  
     3  import "sync"
     4  
     5  type Map struct {
     6  	m map[int]int
     7  	sync.Mutex
     8  }
     9  
    10  func (m *Map) Get(key int) (int, bool) {
    11  	m.Lock()
    12  	defer m.Unlock()
    13  	i, ok := m.m[key]
    14  	return i, ok
    15  }
    16  
    17  func (m *Map) Put(key, value int) {
    18  	m.Lock()
    19  	defer m.Unlock()
    20  	m.m[key] = value
    21  }
    22  
    23  func (m *Map) Len() int {
    24  	return len(m.m)
    25  }
    26  
    27  /*
    28  A: 不能编译
    29  B: 可运行,无并发问题
    30  C: 可运行,有并发问题  答案,需要将len也加上锁
    31  D: panic
    32  */
    33  func main() {
    34  	var wg sync.WaitGroup
    35  	wg.Add(2)
    36  	m := Map{m: make(map[int]int)}
    37  	go func() {
    38  		for i := 0; i < 10000000; i++ {
    39  			m.Put(i, i)
    40  		}
    41  		wg.Done()
    42  	}()
    43  	go func() {
    44  		for i := 0; i < 10000000; i++ {
    45  			m.Len()
    46  		}
    47  		wg.Done()
    48  	}()
    49  	wg.Wait()
    50  
    51  }