search
HomeBackend DevelopmentGolangAn article to introduce you to the basics of Go language concurrency

Introduction

Go language, specifically for Concurrency# A language born with ##, each time you start a micro-thread the cost of creating one is about 2KB Getting Started

Assume a memory stick size of 4G, a micro-thread 2kb1G=1024M=1048576kb 1048576/2=524288, more than half a million

But do you know how much a thread costs in languages ​​such as Java and Python? ???, 2MB starts with the price directly doubled a thousand times

So, get excited and use it as you like Writing a web program in Go is basically equivalent to Nginx

<br>

goroutine

Micro-threads in Go are also called goroutine, goroutine is the

## for parallel processing tasks

#Just like I use two hands to operate two mobile phones at the same time to play games

Instead of playing this with one hand and playing that with one hand, this is a switching method

goroutineScheduling is completed by Go’s runtime,# The essence of ##goroutine is to switch at the code (user mode) level, the cost is very small

Like Java, Threads in languages ​​such as Python are implemented at the operating system (kernel state) level, so the cost is very high

Since goroutine is switched by runtime, AndruntimeAfter optimization by Google’s digital bosses, it’s already a very small cow going up the mountain, and it’s awesome.

<br>

Using goroutine

Using in Gogoroutine is very simple. You just need to add a go before the function you want to call. This is It means starting a goroutine

Normal calling function method

Function

func Say() {
    time.Sleep(time.Second)
    fmt.Println("我在说话说了1s说完了...")
}

main<br>

func main() {
    //开始时间
    var start_time = time.Now()
    //启动10个say说话
    for i := 0; i < 10; i++ {
        Say()
}
    //结束时间
    var end_time = time.Now()
    //计算时间差
    fmt.Println(end_time.Sub(start_time))
}

Execution result<br>

An article to introduce you to the basics of Go language concurrency

##It looped 10 times and took 10s. A bit slow! <br>

<br>

goroutine calling function method

The function is still the same as above Function

main

func main() {
    //开始时间
    var start_time = time.Now()
    //启动10个say说话
    for i := 0; i < 10; i++ {
        go Say()
}
    //结束时间
    var end_time = time.Now()
    //计算时间差
    fmt.Println(end_time.Sub(start_time))
}

Note: Line 6 , with the go keyword added in front, the go keyword means running this function separately in a micro-thread. <br>

Results of the

An article to introduce you to the basics of Go language concurrency

what??? 0s, what’s going on? <br>

<br>

Why does this situation of 0s occur

This It's because, in Go, we use the daemon thread method. What does that mean?

An article to introduce you to the basics of Go language concurrency

In Go, as long as the main function is executed, other micro-threads will be idle.

Just like some monsters, they depend on each other and have a mother. If the mother dies, the baby below will also die.

So how to solve this problem???

<br>

sync .WaitGroup

We found above that some micro-threads were started, but the micro-threads hung up before they had time to execute. This is because main functionIt ran too fast, main finished running, and other micro-threads were automatically closed when Go was running.

Then think about it on the other hand, how can we make main at the endWait a moment, wait until my children are all I’m back and I’m continuing to run.

所以,有一个新的问题,那就是等,祭出法宝sync.WaitGroup

先看一下怎么用

函数

func Say() {
    //函数结束时取消标记
    defer wg.Done()
    //每个函数在启动时加上一个标记
    wg.Add(1)
    //函数开始打上一个标记
    time.Sleep(time.Second*1)
    fmt.Println("我在说话说了1s说完了...")
}

main<br>

var wg  sync.WaitGroup
func main() {
    //开始时间
    var start_time = time.Now()
    //启动10个say说话
    for i := 0; i < 10; i++ {
        go Say()
}
    // 等待所有标记过的微线程执行完毕
    wg.Wait()
    //结束时间
    var end_time = time.Now()
    //计算时间差
    fmt.Println(end_time.Sub(start_time))
}

执行结果<br>

An article to introduce you to the basics of Go language concurrency

可以看到,10个线程同时启动,1s就完了,并且代码相对简单,就算开启10w个,还是1s多一点<br>

这也是为什么很多公司越来越青睐Go的原因。

An article to introduce you to the basics of Go language concurrency

runtime.GOMAXPROCS<br>

这个意思要使用多少个核,默认使用全部核心,性能跑满,但是也有意外的情况,

比如一个机器跑了很多其他任务,Go写的这个是不太重要的任务,但是是计算型的,这时候理论来说是不尽量挤兑别人的算力

所以要限制一下当前程序使用电脑的算力

代码

func main() {
    //本机的cpu个数
    var cpuNum = runtime.NumCPU()
    fmt.Println(cpuNum)
    //设置Go使用cpu个数
    runtime.GOMAXPROCS(4)
}

<br>

总结<br>

上述我们学习了Go的并发,学习了

  • 如何创建一个协程(goroutine)。

  • 为什么需要sync.WaitGroup

  • 设置当前程序使用CPU核数。

The above is the detailed content of An article to introduce you to the basics of Go language concurrency. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:Go语言进阶学习. If there is any infringement, please contact admin@php.cn delete
Golang vs. Python: The Pros and ConsGolang vs. Python: The Pros and ConsApr 21, 2025 am 12:17 AM

Golangisidealforbuildingscalablesystemsduetoitsefficiencyandconcurrency,whilePythonexcelsinquickscriptinganddataanalysisduetoitssimplicityandvastecosystem.Golang'sdesignencouragesclean,readablecodeanditsgoroutinesenableefficientconcurrentoperations,t

Golang and C  : Concurrency vs. Raw SpeedGolang and C : Concurrency vs. Raw SpeedApr 21, 2025 am 12:16 AM

Golang is better than C in concurrency, while C is better than Golang in raw speed. 1) Golang achieves efficient concurrency through goroutine and channel, which is suitable for handling a large number of concurrent tasks. 2)C Through compiler optimization and standard library, it provides high performance close to hardware, suitable for applications that require extreme optimization.

Why Use Golang? Benefits and Advantages ExplainedWhy Use Golang? Benefits and Advantages ExplainedApr 21, 2025 am 12:15 AM

Reasons for choosing Golang include: 1) high concurrency performance, 2) static type system, 3) garbage collection mechanism, 4) rich standard libraries and ecosystems, which make it an ideal choice for developing efficient and reliable software.

Golang vs. C  : Performance and Speed ComparisonGolang vs. C : Performance and Speed ComparisonApr 21, 2025 am 12:13 AM

Golang is suitable for rapid development and concurrent scenarios, and C is suitable for scenarios where extreme performance and low-level control are required. 1) Golang improves performance through garbage collection and concurrency mechanisms, and is suitable for high-concurrency Web service development. 2) C achieves the ultimate performance through manual memory management and compiler optimization, and is suitable for embedded system development.

Is Golang Faster Than C  ? Exploring the LimitsIs Golang Faster Than C ? Exploring the LimitsApr 20, 2025 am 12:19 AM

Golang performs better in compilation time and concurrent processing, while C has more advantages in running speed and memory management. 1.Golang has fast compilation speed and is suitable for rapid development. 2.C runs fast and is suitable for performance-critical applications. 3. Golang is simple and efficient in concurrent processing, suitable for concurrent programming. 4.C Manual memory management provides higher performance, but increases development complexity.

Golang: From Web Services to System ProgrammingGolang: From Web Services to System ProgrammingApr 20, 2025 am 12:18 AM

Golang's application in web services and system programming is mainly reflected in its simplicity, efficiency and concurrency. 1) In web services, Golang supports the creation of high-performance web applications and APIs through powerful HTTP libraries and concurrent processing capabilities. 2) In system programming, Golang uses features close to hardware and compatibility with C language to be suitable for operating system development and embedded systems.

Golang vs. C  : Benchmarks and Real-World PerformanceGolang vs. C : Benchmarks and Real-World PerformanceApr 20, 2025 am 12:18 AM

Golang and C have their own advantages and disadvantages in performance comparison: 1. Golang is suitable for high concurrency and rapid development, but garbage collection may affect performance; 2.C provides higher performance and hardware control, but has high development complexity. When making a choice, you need to consider project requirements and team skills in a comprehensive way.

Golang vs. Python: A Comparative AnalysisGolang vs. Python: A Comparative AnalysisApr 20, 2025 am 12:17 AM

Golang is suitable for high-performance and concurrent programming scenarios, while Python is suitable for rapid development and data processing. 1.Golang emphasizes simplicity and efficiency, and is suitable for back-end services and microservices. 2. Python is known for its concise syntax and rich libraries, suitable for data science and machine learning.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor