Table of Contents
I. Goroutines: A Deep Dive into Go's Concurrency Model
II. Understanding Goroutine's Internal Mechanics
Conceptual Foundations
Concurrency vs. Parallelism
Processes and Threads
Coroutines
The GPM Scheduling Model
Scheduling in Action
III. Working with Goroutines
Basic Usage
Practical Examples
Example 1: Simple Goroutine Calculation
Goroutine Error Handling
Synchronizing Goroutines
Example 1: Using sync.WaitGroup
Example 2: Using Channels for Synchronization
Inter-Goroutine Communication
Example: Producer-Consumer Pattern
Leapcell: A Serverless Platform for Go
Home Backend Development Golang Go&#s Concurrency Decoded: Goroutine Scheduling

Go&#s Concurrency Decoded: Goroutine Scheduling

Jan 14, 2025 pm 10:08 PM

Go

I. Goroutines: A Deep Dive into Go's Concurrency Model

Goroutines are a cornerstone of Go's design, providing a powerful mechanism for concurrent programming. As lightweight coroutines, they simplify parallel task execution. Launching a goroutine is straightforward: simply prefix a function call with the go keyword, initiating asynchronous execution. The main program continues without waiting for the goroutine's completion.

go func() { // Launch a goroutine using the 'go' keyword
    // ... code to be executed concurrently ...
}()
Copy after login
Copy after login

II. Understanding Goroutine's Internal Mechanics

Conceptual Foundations

Concurrency vs. Parallelism

  • Concurrency: The ability to manage multiple tasks seemingly simultaneously on a single CPU. The CPU rapidly switches between tasks, creating the illusion of parallel execution. While microscopically sequential, macroscopically it appears concurrent.

  • Parallelism: True simultaneous execution of multiple tasks across multiple CPUs, eliminating CPU resource contention.

Processes and Threads

  • Process: A self-contained execution environment with its own resources (memory, files, etc.). Switching between processes is resource-intensive, requiring kernel-level intervention.

  • Thread: A lightweight unit of execution within a process, sharing the process's resources. Thread switching is less overhead than process switching.

Coroutines

Coroutines maintain their own register context and stack. Switching between coroutines involves saving and restoring this state, allowing them to resume execution from where they left off. Unlike processes and threads, coroutine management is handled within the user program, not the operating system. Goroutines are a specific type of coroutine.

The GPM Scheduling Model

Go's efficient concurrency relies on the GPM scheduling model. Four key components are involved: M, P, G, and Sched (Sched is not depicted in the diagrams).

  • M (Machine): A kernel-level thread. Goroutines run on Ms.

  • G (Goroutine): A single goroutine. Each G has its own stack, instruction pointer, and other scheduling-related information (e.g., channels it's waiting on).

  • P (Processor): A logical processor that manages and executes goroutines. It maintains a run queue of ready goroutines.

  • Sched (Scheduler): The central scheduler, managing M and G queues and ensuring efficient resource allocation.

Scheduling in Action

Go&#s Concurrency Decoded: Goroutine Scheduling

The diagram shows two OS threads (M), each with a processor (P) executing a goroutine.

  • GOMAXPROCS() controls the number of Ps (and thus the true concurrency level).

  • The gray Gs are ready but not yet running. P manages this run queue.

  • Launching a goroutine adds it to P's run queue.

Go&#s Concurrency Decoded: Goroutine Scheduling

If an M0 is blocked, P switches to M1 (which might be retrieved from a thread cache).

Go&#s Concurrency Decoded: Goroutine Scheduling

If a P completes its tasks quickly, it might steal work from other Ps to maintain efficiency.

III. Working with Goroutines

Basic Usage

Set the number of CPUs for goroutine execution (the default setting in recent Go versions is usually sufficient):

go func() { // Launch a goroutine using the 'go' keyword
    // ... code to be executed concurrently ...
}()
Copy after login
Copy after login

Practical Examples

Example 1: Simple Goroutine Calculation

num := runtime.NumCPU() // Get the number of logical CPUs
runtime.GOMAXPROCS(num) // Set the maximum number of concurrently running goroutines
Copy after login

Goroutine Error Handling

Unhandled exceptions in a goroutine can terminate the entire program. Use recover() within a defer statement to handle panics:

package main

import (
    "fmt"
    "runtime"
)

func cal(a, b int) {
    c := a + b
    fmt.Printf("%d + %d = %d\n", a, b, c)
}

func main() {
    runtime.GOMAXPROCS(runtime.NumCPU())
    for i := 0; i < 10; i++ {
        go cal(i, i+1)
    }
    //Note:  The main function exits before goroutines complete in this example.  See later sections for synchronization.
}
Copy after login

Synchronizing Goroutines

Since goroutines run asynchronously, the main program might exit before they complete. Use sync.WaitGroup or channels for synchronization:

Example 1: Using sync.WaitGroup

package main

import (
    "fmt"
)

func addele(a []int, i int) {
    defer func() {
        if r := recover(); r != nil {
            fmt.Println("Error in addele:", r)
        }
    }()
    a[i] = i // Potential out-of-bounds error if i is too large
    fmt.Println(a)
}

func main() {
    a := make([]int, 4)
    for i := 0; i < 5; i++ {
        go addele(a, i)
    }
    // ... (add synchronization to wait for goroutines to finish) ...
}
Copy after login

Example 2: Using Channels for Synchronization

package main

import (
    "fmt"
    "sync"
)

func cal(a, b int, wg *sync.WaitGroup) {
    defer wg.Done()
    c := a + b
    fmt.Printf("%d + %d = %d\n", a, b, c)
}

func main() {
    var wg sync.WaitGroup
    for i := 0; i < 10; i++ {
        wg.Add(1)
        go cal(i, i+1, &wg)
    }
    wg.Wait()
}
Copy after login

Inter-Goroutine Communication

Channels facilitate communication and data sharing between goroutines. Global variables can also be used, but channels are generally preferred for better concurrency control.

Example: Producer-Consumer Pattern

package main

import (
    "fmt"
)

func cal(a, b int, ch chan bool) {
    c := a + b
    fmt.Printf("%d + %d = %d\n", a, b, c)
    ch <- true // Signal completion
}

func main() {
    ch := make(chan bool, 10) // Buffered channel to avoid blocking
    for i := 0; i < 10; i++ {
        go cal(i, i+1, ch)
    }
    for i := 0; i < 10; i++ {
        <-ch // Wait for each goroutine to finish
    }
}
Copy after login

Leapcell: A Serverless Platform for Go

Leapcell is a recommended platform for deploying Go services.

Go

Key Features:

  1. Multi-Language Support: JavaScript, Python, Go, Rust.
  2. Free Unlimited Projects: Pay-as-you-go pricing.
  3. Cost-Effective: No idle charges.
  4. Developer-Friendly: Intuitive UI, automated CI/CD, real-time metrics.
  5. Scalable and High-Performance: Auto-scaling, zero operational overhead.

Go

Learn more in the documentation!

Leapcell Twitter: https://www.php.cn/link/7884effb9452a6d7a7a79499ef854afd

The above is the detailed content of Go&#s Concurrency Decoded: Goroutine Scheduling. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are the vulnerabilities of Debian OpenSSL What are the vulnerabilities of Debian OpenSSL Apr 02, 2025 am 07:30 AM

OpenSSL, as an open source library widely used in secure communications, provides encryption algorithms, keys and certificate management functions. However, there are some known security vulnerabilities in its historical version, some of which are extremely harmful. This article will focus on common vulnerabilities and response measures for OpenSSL in Debian systems. DebianOpenSSL known vulnerabilities: OpenSSL has experienced several serious vulnerabilities, such as: Heart Bleeding Vulnerability (CVE-2014-0160): This vulnerability affects OpenSSL 1.0.1 to 1.0.1f and 1.0.2 to 1.0.2 beta versions. An attacker can use this vulnerability to unauthorized read sensitive information on the server, including encryption keys, etc.

How do you use the pprof tool to analyze Go performance? How do you use the pprof tool to analyze Go performance? Mar 21, 2025 pm 06:37 PM

The article explains how to use the pprof tool for analyzing Go performance, including enabling profiling, collecting data, and identifying common bottlenecks like CPU and memory issues.Character count: 159

How do you write unit tests in Go? How do you write unit tests in Go? Mar 21, 2025 pm 06:34 PM

The article discusses writing unit tests in Go, covering best practices, mocking techniques, and tools for efficient test management.

What libraries are used for floating point number operations in Go? What libraries are used for floating point number operations in Go? Apr 02, 2025 pm 02:06 PM

The library used for floating-point number operation in Go language introduces how to ensure the accuracy is...

What is the problem with Queue thread in Go's crawler Colly? What is the problem with Queue thread in Go's crawler Colly? Apr 02, 2025 pm 02:09 PM

Queue threading problem in Go crawler Colly explores the problem of using the Colly crawler library in Go language, developers often encounter problems with threads and request queues. �...

What is the go fmt command and why is it important? What is the go fmt command and why is it important? Mar 20, 2025 pm 04:21 PM

The article discusses the go fmt command in Go programming, which formats code to adhere to official style guidelines. It highlights the importance of go fmt for maintaining code consistency, readability, and reducing style debates. Best practices fo

PostgreSQL monitoring method under Debian PostgreSQL monitoring method under Debian Apr 02, 2025 am 07:27 AM

This article introduces a variety of methods and tools to monitor PostgreSQL databases under the Debian system, helping you to fully grasp database performance monitoring. 1. Use PostgreSQL to build-in monitoring view PostgreSQL itself provides multiple views for monitoring database activities: pg_stat_activity: displays database activities in real time, including connections, queries, transactions and other information. pg_stat_replication: Monitors replication status, especially suitable for stream replication clusters. pg_stat_database: Provides database statistics, such as database size, transaction commit/rollback times and other key indicators. 2. Use log analysis tool pgBadg

Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Apr 02, 2025 am 09:12 AM

Backend learning path: The exploration journey from front-end to back-end As a back-end beginner who transforms from front-end development, you already have the foundation of nodejs,...

See all articles