SoFunction
Updated on 2025-03-03

Golang's method of using channel to coordinate the coordinating process

Preface

The concurrent programming in go is throughgoroutineTo achieve, usechannel (pipe)Data can be passed between coroutines to achieve coordination and synchronization of coroutines.

use

Create a new pipeline and usemake channelTo build

// Build a pipeline with cache length 8ch := make(chan int ,8)
// Writech <- 10
// take outnumber := <-ch
// closureclose(ch)

Note: When fetching data, if it is not fetched, the code execution will be blocked. If it is not fetched, it will be a deadlock.

Implement the producer and consumer model

Two producer coroutines and one consumer coroutine

usewaitGroup

func main() {  
    ch := make(chan int, 100)  
    wg := {}  
    (2)  
    // Producer    go func() {  
        defer ()  
        // Write data        for i := 0; i < 10; i++ {  
            ch <- i  
        }  
    }()  
    // Producer    go func() {  
        defer ()  
        // Write data        for i := 0; i < 10; i++ {  
            ch <- i  
        }  
    }()  
    wg2 := {}  
    (1)  
    // Consumer    go func() {  
        sum := 0  
        ("sum %d \n", sum)  
        for {  
            // I'll wait here            temp, ok := <-ch  
            // close and the pipeline is empty, ok = false            if !ok {    
                break  
            } else {  
                sum += temp  
            }  
        }  
        ("sum %d \n", sum)  
        ()  
    }()  
    // Wait for the end of the two producers    ()  
    // After the production data, the consumer has finished reading it in parallel. At this time, the pipeline can be closed and the for loop will be broken.    close(ch)  
    // Wait for the end of the consumer coroutine    ()  
}

Use the pipeline to change the wg2-related code

func main() {  
    //... 
    //...
    ch2 := make(chan struct{}, 0)  
    go func() {  
        sum := 0  
        ("sum %d \n", sum)  
        for {  
            // I'll wait here            temp, ok := <- ch  
            // close and the pipeline is empty, ok = false            if !ok {  
                break  
            } else {  
                sum += temp  
            }  
        }  
        ("sum %d \n", sum)  
        ch2 <- struct{}{}  
    }()  
    // Wait for the end of the two producers    ()  
    // Close the pipeline    close(ch)  
    // Wait for the end of the consumer coroutine    <-ch2
}

Practical interview questions: "Print numbers and letters alternately"

topic

Use twogoroutineAlternately print sequences, onegoroutinePrint the number, another onegoroutinePrint letters, the final effect is as follows:

12AB34CD56EF78GH910IJ1112KL1314MN1516OP1718QR1920ST2122UV2324WX2526YZ2728

Problem-solving ideas

Use channel blocking to coordinate threads to achieve the effect of thread cross-execution.

Code

func main() {  
    letter, number := make(chan bool), make(chan bool)  
    wait := {}  
    go func() {  
        i := 1  
        for {  
            if <-number {  
                (i)  
                i++  
                (i)  
                i++  
                letter <- true  
            }  
        }  
    }()  
    (1)  
    go func() {  
        // Obtain ASCII code        i := 'A'  
        for {  
            if <-letter {  
                // If Z is currently exceeded, no need to print again                if i > 'Z' {  
                    // Stop waiting and jump out of the loop                    ()  
                    break  
                }  
                // Force ASCII code to letter output                (string(i))  
                i++  
                (string(i))  
                i++  
                number <- true  
            }  
        }  
    }()  
    // Blocking of release digital printing    number <- true  
    // Wait for the main thread to be closed    ()  
}

Actually, it can also bewaitGroupChange to a pipe

func main() {  
    letter, number := make(chan bool), make(chan bool)  
    // Define another pipeline to wait, replacing the role of waitGroup    wait := make(chan bool)
    // Print numbers    go func() {  
        i := 1  
        for {  
            if <-number {  
                (i)  
                i++  
                (i)  
                i++  
                letter <- true  
            }  
        }  
    }()  
    // Print letters    go func() {  
        // Obtain ASCII code        i := 'A'  
        for {  
            if <-letter {  
                if i > 'Z' {  
                    wait <- true  
                    break  
                }  
                // Force ASCII code to letter output                (string(i))  
                i++  
                (string(i))  
                i++  
                number <- true  
            }  
        }  
    }()  
    number <- true  
    // Wait for the pipeline to get the value    <- wait 
}

This is the end of this article about Golang's detailed explanation of the method of using channel coordination coordinating coordinating. For more related content of Golang channel coordination coordinating coordinating coordinating, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!