SoFunction
Updated on 2025-03-05

Go language blocking function and non-blocking function implementation

1. Blocking function

The blocking function will hang itself before it gets the result, blocking the current thread, as shown below.

package main

import (
    "fmt"
    "time"
)

func func1() error {
    for {
        ()
        //Or after doing other operations, jump out of the loop through break    }
    return nil
}

func main() {
    err := func1()
    (err)   //Unable to print err when the for loop ends in func1}

Among them, func1 is a blocking function, because when the main function calls func1, it needs to wait for the func1 function for the end of the loop to get the return value. Before the func1 function returns, the main function cannot do other things. The main function and func1 function here are both in the same thread, so the func1 function will block the current thread.

2. Non-blocking functions

Non-blocking functions do not block the current thread.

package main

import (
    "fmt"
    "time"
)

func func1() error {
    go func() {
        for {
            ()
            //Or after doing other operations, jump out of the loop through break        }
    }()
    return nil
}

func main() {
    err := func1()
    (err) //Immediately print out <nil>}

Among them, func1 is a non-blocking function. For main function, after calling func1, you don’t need to care whether the for loop in func1 has ended. It can get the result immediately, so that you can do other things you want to do. Of course, the main function here, that is, the main thread, needs to ensure that the current thread will not hang up.

3. Summary

From the above two examples, it can be seen that non-blocking functions are actually implemented through coroutines in the go language.

This is the article about the implementation of go language blocking functions and non-blocking functions. For more related go language blocking functions and non-blocking functions, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!