前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Go-标准库-sync(四)

Go-标准库-sync(四)

原创
作者头像
堕落飞鸟
发布2023-04-22 08:56:10
1260
发布2023-04-22 08:56:10
举报
文章被收录于专栏:飞鸟的专栏

原子操作(atomic)

原子操作(atomic)是 sync/atomic 包中的一组函数,用于原子地读取和修改变量的值。原子操作不会被其它 goroutine 中断,因此不需要使用互斥锁进行保护。

sync/atomic 包中的主要函数有:AddInt32()AddInt64()AddUint32()AddUint64()AddUintptr()CompareAndSwapInt32()CompareAndSwapInt64()CompareAndSwapPointer()LoadInt32()LoadInt64()LoadPointer()StoreInt32()StoreInt64()StorePointer()

下面是一个原子操作的示例代码:

代码语言:javascript
复制
package main

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

var count int32

func increment() {
	atomic.AddInt32(&count, 1)
}

func main() {
	for i := 0; i < 100; i++ {
		go increment()
	}
	time.Sleep(time.Second)
	fmt.Println("Count:", count)
}

在上面的示例代码中,我们定义了一个全局变量 count,并使用 atomic.AddInt32() 函数在多个 goroutine 中原子地将其加 1。在 main() 函数中,我们启动了 100 个 goroutine 来调用 increment() 函数,最后使用 time.Sleep() 函数等待 1 秒钟,然后打印出 count 的值。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 原子操作(atomic)
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档