Go语言(Golang)如何处理高并发?

Go语言通过goroutine和channel提供了高并发的解决方案。

  1. 使用goroutine

Goroutine 是 Go 语言中并发的核心。goroutine 是轻量级的线程,它们在一个线程上下文中启动,并由 Go 的运行时管理。创建一个 goroutine 的开销极低。




package main
 
import (
    "fmt"
    "time"
)
 
func hello() {
    fmt.Println("Hello world goroutine")
}
 
func main() {
    go hello() // 创建一个goroutine
 
    fmt.Println("main function")
 
    time.Sleep(1 * time.Second) // 等待goroutine执行完成
}
  1. 使用channel

Channel 是 Go 语言中的一个类型,你可以通过它来发送或者接收值,这些值可以在不同的 goroutine 之间同步传递。




package main
 
import (
    "fmt"
    "time"
)
 
func printNumbers(numbers chan int) {
    for number := range numbers {
        fmt.Println(number)
    }
}
 
func main() {
    numbers := make(chan int, 5)
 
    go printNumbers(numbers)
 
    for i := 0; i < 5; i++ {
        numbers <- i
        time.Sleep(time.Second) // 模拟一些处理时间
    }
 
    close(numbers) // 关闭channel,通知printNumbers函数结束循环
}
  1. 使用mutex和atomic

在并发编程中,我们还需要处理共享数据的竞争问题。Go 语言提供了 sync 包中的 mutex 和 rwmutex 类型,以及 sync/atomic 包中的原子函数来处理这些问题。




package main
 
import (
    "fmt"
    "sync"
    "sync/atomic"
)
 
var counter int32
var wg sync.WaitGroup
 
func increment() {
    defer wg.Done()
    for i := 0; i < 2; i++ {
        atomic.AddInt32(&counter, 1)
    }
}
 
func main() {
    wg.Add(2)
    go increment()
    go increment()
    wg.Wait()
 
    fmt.Println("Counter:", counter)
}
  1. 使用超时和取消

在 Go 语言中,通过 context 包可以实现对 goroutine 的超时管理和取消管理。




package main
 
import (
    "context"
    "fmt"
    "time"
)
 
func longRunningOperation(ctx context.Context) {
    select {
    case <-ctx.Done():
        fmt.Println("Operation canceled")
        return
    case <-time.After(5 * time.Second):
        fmt.Println("Operation completed")
    }
}
 
func main() {
    ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
    defer cancel()
 
    longRunningOperation(ctx)
}
  1. 使用池

使用 sync.Pool 可以提高大量 goroutine 之间共享数据的效率。




package main
 
import (
    "fmt"
    "sync"
)
 
var pool = sync.Pool{
    New: func() interface{} {
        return "Initial value"
    },
}
 
func getValue() interface{} {
    return pool.Get()
}
 
func setValue(value interface{}) {
    pool.Put(value)
}
 
func main() {
    setValue("New value")
    fmt.Println(getValue())
}
  1. 使用select处理多个channel
最后修改于:2024年08月15日 22:12

评论已关闭

推荐阅读

Vue中使用mind-map实现在线思维导图
2024年08月04日
VUE
Web前端最全Vue实现免密登录跳转的方式_vue怎么样不登录返回首页,最强技术实现
2024年08月04日
VUE
vue3 项目搭建教程(基于create-vue,vite,Vite + Vue)
2024年08月04日
VUE
Vue-颜色选择器实现方案——>Vue-Color( 实战*1+ Demo*7)
2024年08月04日
VUE
Vue项目卡顿慢加载?这些优化技巧告诉你!_vue数据多渲染卡顿
2024年08月04日
VUE
vue中的keep-alive详解与应用场景
2024年08月04日
VUE
Vue、React实现excel导出功能(三种实现方式保姆级讲解)
2024年08月04日
vue-office/docx插件实现docx文件预览
2024年08月04日
VUE
java调用js文件的两种方法(支持V8引擎)
2024年08月04日
JavaScript:解决计算精度问题/mathjs/bignumber.js/big.js/decimal.js
2024年08月04日
两周从爬虫小白变大神 _yjs_js_security_passport
2024年08月04日
JS笔记(对象、函数、数组)
2024年08月04日
Markdown.js:强大的纯JavaScript Markdown解析器
2024年08月04日
Vue项目:js模拟点击a标签下载文件并重命名,URL文件地址下载方法、请求接口下载文件方法总结。
2024年08月04日
vue 父组件怎么获取子组件里面的data数据
2024年08月04日
VUE
个人开发实现AI套壳网站快速搭建(Vue+elementUI+SpringBoot)
2024年08月04日
el-table 表格封装并改造实现单元格可编辑
2024年08月04日
none
nodejs环境下创建vue项目、SSH密钥登陆!!!
2024年08月04日
vue+quill+element-ui实现视频、图片上传及缩放保姆级教程,轻松使用富文本
2024年08月04日
【three.js】22. Imported Models导入模型
2024年08月04日