0
点赞
收藏
分享

微信扫一扫

Golang 并发编程备忘记录-Mutex-01

岛上码农 2024-02-06 阅读 13

Mutex的Lock和Unlock

package main

import (
	"fmt"
	"sync"
)

// Count 临界资源,mutex字段嵌入结构体
type Count struct {
	CounterType int
	Name        string

	// mutex字段一般放在临界资源的上面
	sync.Mutex
	Counter int
}

// Incr 加锁、解锁、自增操作
func (c *Count) Incr() {
	c.Lock()
	c.Counter++
	c.Unlock()
}

// GetCount 获取值操作,同样加锁
func (c *Count) GetCount() int {
	c.Lock()
	defer c.Unlock()

	return c.Counter
}

func main() {
	var wg sync.WaitGroup
	var count Count

	wg.Add(10)
	for i := 0; i < 10; i++ {
		go func() {
			defer wg.Done()
			for j := 0; j < 10000; j++ {
				count.Incr()
			}
		}()
	}

	wg.Wait()
	fmt.Println(count.GetCount())
}


举报

相关推荐

0 条评论