go-互斥锁及原子函数

简介: 用于解决并发函数的竞争状态问题。。。 package main import ( "fmt" "runtime" "sync" "sync/atomic" ) var ( counter int64 wg sync.

用于解决并发函数的竞争状态问题。。。

package main

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

var (
	counter int64
	wg      sync.WaitGroup
	mutex   sync.Mutex
)

func main() {

	wg.Add(2)

	fmt.Println("Create Goroutines")
	go incCount(1)
	go incCount(2)

	fmt.Println("Waiting To Finish")
	wg.Wait()

	fmt.Println("Final Counter: ", counter)

}

func incCount(id int) {
	defer wg.Done()
	for count := 0; count < 2; count++ {
		atomic.AddInt64(&counter, 1)
		//value := counter
		runtime.Gosched()
		//value++
		//counter = value
	}

	mutex.Lock()
	{
		value := counter
		runtime.Gosched()
		value++
		counter = value
	}
	mutex.Unlock()
}

  

目录
相关文章
|
4月前
|
Go
go的并发初体验、加锁、异步
go的并发初体验、加锁、异步
|
1月前
|
Go
go函数
go函数
31 10
|
28天前
|
编译器 Go C++
Go to Learn Go之函数
Go to Learn Go之函数
21 0
|
1月前
|
编译器 Go 索引
Go数组、多维数组和切片(动态数组),及常用函数len(),cap(),copy(),append()在切片中的使用
本文介绍了Go语言中数组、多维数组和切片(动态数组)的基本概念和操作,包括数组的定义、初始化、访问,多维数组的定义和访问,以及切片的创建、使用和扩容。同时,还讲解了切片中常用的函数len()、cap()、copy()和append()的使用方法。
|
2月前
|
Prometheus Cloud Native Go
Go 1.22 标准库 slices 新增函数和一些旧函数增加新特性
Go 1.22 标准库 slices 新增函数和一些旧函数增加新特性
|
2月前
|
安全 Go API
go语言中的Atomic操作与sema锁
在并发编程中,确保数据一致性和程序正确性是关键挑战。Go语言通过协程和通道提供强大支持,但在需精细控制资源访问时,Atomic操作和sema锁变得至关重要。Atomic操作确保多协程环境下对共享资源的访问是不可分割的,如`sync/atomic`包中的`AddInt32`等函数,底层利用硬件锁机制实现。sema锁(信号量锁)控制并发协程数量,其核心是一个uint32值,当大于零时通过CAS操作实现锁的获取与释放;当为零时,sema锁管理协程休眠队列。这两种机制共同保障了Go语言并发环境下的数据完整性和程序稳定性。
|
2月前
|
安全 编译器 Go
Go 1.21: 泛型函数的全面回顾
Go 1.21: 泛型函数的全面回顾
|
2月前
|
Go
深入理解 Go 中的 new() 和 make() 函数
深入理解 Go 中的 new() 和 make() 函数
|
2月前
|
安全 Go 调度
[go 面试] 深入理解并发控制:掌握锁的精髓
[go 面试] 深入理解并发控制:掌握锁的精髓
|
2月前
|
设计模式 Java 数据库连接