golang并发笔记

本文深入探讨了 Go 语言中的并发控制机制,包括互斥锁(sync.Mutex)、原子操作(sync/atomic)以及 sync.WaitGroup 的使用。通过示例代码展示了它们在并发场景下的应用,帮助读者理解如何在 Go 中确保数据安全和正确同步。
// 互斥锁
package main

import (
	"bytes"
	"fmt"
	"runtime"
	"strconv"
	"sync"
)

func goid() uint64 {
	b := make([]byte, 64)
	b = b[:runtime.Stack(b, false)]
	b = bytes.TrimPrefix(b, []byte("goroutine "))
	b = b[:bytes.IndexByte(b, ' ')]
	n, _ := strconv.ParseUint(string(b), 10, 64)
	return n
}

func main() {
	runtime.GOMAXPROCS(runtime.NumCPU())
	const taskNum = 2
	cnt := uint64(0)
	var wg sync.WaitGroup
	var mtx sync.Mutex
	wg.Add(taskNum)
	fmt.Printf("cnt: %p, wg: %p \n", &cnt, &wg)
	for i := 0; i < taskNum; i++ {
		go func(id int, counter *uint64, wg *sync.WaitGroup, mtx *sync.Mutex) {
			defer wg.Done()
			for c := 0; c < 10; c++ {
				mtx.Lock()
				*counter += 1
				x := *counter
				mtx.Unlock()
				fmt.Printf("goid: %d, cnt: %d, wg: %p\n", goid(), x, wg)
				runtime.Gosched()
			}
		}(i, &cnt, &wg, &mtx)
	}
	wg.Wait()
	fmt.Println("end")
}
// 原子操作
package main

import (
	"bytes"
	"fmt"
	"runtime"
	"strconv"
	"sync"
	"sync/atomic"
	"time"
)

func goid() uint64 {
	b := make([]byte, 64)
	b = b[:runtime.Stack(b, false)]
	b = bytes.TrimPrefix(b, []byte("goroutine "))
	b = b[:bytes.IndexByte(b, ' ')]
	n, _ := strconv.ParseUint(string(b), 10, 64)
	return n
}

func main() {
	runtime.GOMAXPROCS(runtime.NumCPU())
	const taskNum = 2
	cnt := uint64(0)
	var wg sync.WaitGroup
	wg.Add(taskNum)
	fmt.Printf("cnt: %p, wg: %p \n", &cnt, &wg)
	for i := 0; i < taskNum; i++ {
		go func(wg *sync.WaitGroup, id int, cnt *uint64) {
			defer wg.Done()
			for {
				fmt.Printf("goid: %d work \n", goid())
				if atomic.LoadUint64(cnt) == 1 {
					fmt.Printf("goid: %d break \n", goid())
					break
				}
				time.Sleep(time.Second * 1)
				runtime.Gosched()
			}

		}(&wg, i, &cnt)
	}
	time.Sleep(time.Second * 10)
	atomic.StoreUint64(&cnt, 1)

	wg.Wait()
	fmt.Println("end")
}
// WaitGroup和atomic.AddUint64
package main

import (
	"bytes"
	"fmt"
	"runtime"
	"strconv"
	"sync"
	"sync/atomic"
)

func goid() uint64 {
	b := make([]byte, 64)
	b = b[:runtime.Stack(b, false)]
	b = bytes.TrimPrefix(b, []byte("goroutine "))
	b = b[:bytes.IndexByte(b, ' ')]
	n, _ := strconv.ParseUint(string(b), 10, 64)
	return n
}

func main() {
	runtime.GOMAXPROCS(runtime.NumCPU())
	const taskNum = 5
	cnt := uint64(0)
	var wg sync.WaitGroup
	wg.Add(taskNum)
	fmt.Printf("cnt: %p, wg: %p \n", &cnt, &wg)
	for i := 0; i < taskNum; i++ {
		go func(id int, counter *uint64, wg *sync.WaitGroup) {
			defer wg.Done()
			for c := 0; c < 10; c++ {
				x := atomic.AddUint64(counter, 1)
				fmt.Printf("goid: %d, cnt: %d, wg: %p\n", goid(), x, wg)
				runtime.Gosched()
			}
		}(i, &cnt, &wg)
	}
	wg.Wait()
	fmt.Println("end")
}

// sync.WaitGroup
package main

import (
	"bytes"
	"fmt"
	"runtime"
	"strconv"
	"sync"
)

func goid() uint64 {
	b := make([]byte, 64)
	b = b[:runtime.Stack(b, false)]
	b = bytes.TrimPrefix(b, []byte("goroutine "))
	b = b[:bytes.IndexByte(b, ' ')]
	n, _ := strconv.ParseUint(string(b), 10, 64)
	return n
}

func main() {
	runtime.GOMAXPROCS(runtime.NumCPU())
	const taskNum = 5
	var wg sync.WaitGroup
	wg.Add(taskNum)
	fmt.Printf("start, wg: %p \n", &wg)
	for i := 0; i < taskNum; i++ {
		go func(wg *sync.WaitGroup, i int) {
			defer wg.Done()
			fmt.Printf("goid: %d, i: %d, wg: %p \n", goid(), i, wg)
		}(&wg, i)
	}
	wg.Wait()
	fmt.Println("end")
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值