Table of Contents
Go concurrency (multi-threading)
Home Backend Development Golang Is single-threading a feature of the Go language?

Is single-threading a feature of the Go language?

Jan 06, 2023 am 11:17 AM
golang go language

Single threading is not a feature of the go language, the go language is multi-threaded. Golang's thread model is the MPG model. Overall, Go processes and kernel threads have a many-to-many correspondence, so Go must be in multi-thread mode; M and kernel threads correspond 1 to 1, and multiple Gs correspond to multiple M Correspondingly, P refers to context resources.

Is single-threading a feature of the Go language?

The operating environment of this tutorial: Windows 7 system, GO version 1.18, Dell G3 computer.

Single threading is not a feature of the go language, the go language is multi-threaded. If it’s single-threaded, it’s still embarrassing. It’s a language that’s said to be born for high concurrency in the multi-core era?

Golang’s thread model is the MPG model. Generally speaking, Go processes and kernel threads have a many-to-many correspondence, so first of all they must be multi-threaded. Among them, M corresponds to the kernel thread 1:1, and then multiple G corresponds to multiple M. P refers to the context resource, not much to say. When does the number of M (or kernel threads) increase? That is, when the current number of M cannot be scheduled to move all the current G, a new M will be used to process it.

Go concurrency (multi-threading)

Some people compare Go to the C language of the 21st century. First, it is because the Go language is simple in design. Second, it is the most popular language in the 21st century. The important thing is parallel programming, and Go supports parallelism from the language level.

goroutine

goroutine is the core of Go's parallel design. In the final analysis, goroutine is actually a thread, but it is smaller than a thread. A dozen goroutines may be reflected in five or six threads at the bottom. The Go language helps you realize memory sharing among these goroutines. Executing goroutine requires very little stack memory (about 4~5KB), and of course it will scale according to the corresponding data. Because of this, thousands of concurrent tasks can be run simultaneously. Goroutine is easier to use, more efficient, and lighter than thread.

Goroutine is a thread manager managed by Go's runtime. Goroutine is implemented through the go keyword, which is actually an ordinary function.

go hello(a, b, c)
Copy after login

Start a goroutine through the keyword go. Let's take a look at an example

package main

import (
    "fmt"
    "runtime"
)

func say(s string) {
    for i := 0; i < 5; i++ {
        runtime.Gosched()
        fmt.Println(s)
    }
}

func main() {
    go say("world") //开一个新的Goroutines执行
    say("hello") //当前Goroutines执行
}

// 以上程序执行后将输出:
// hello
// world
// hello
// world
// hello
// world
// hello
// world
// hello
Copy after login

We can see that the go keyword can easily implement concurrent programming. The multiple goroutines above run in the same process and share memory data. However, we must follow the design: do not communicate through sharing, but share through communication.

runtime.Gosched() means to let the CPU give up the time slice to others and continue to resume execution of the goroutine at some time next time.

By default, the scheduler only uses a single thread, which means that only concurrency is achieved. To take advantage of the parallelism of multi-core processors, we need to explicitly call runtime.GOMAXPROCS(n) in our program to tell the scheduler to use multiple threads at the same time. GOMAXPROCS sets the maximum number of system threads that can run logic code simultaneously, and returns the previous setting. If n < 1, the current setting will not be changed. This will be removed when scheduling is improved in future versions of Go.

channels

goroutine runs in the same address space, so access to shared memory must be synchronized . So how to communicate data between goroutines? Go provides a good communication mechanism channel. A channel can be compared to a bidirectional pipe in a Unix shell: you can send or receive values ​​through it. These values ​​can only be of a specific type: channel type. When you define a channel, you also need to define the type of value sent to the channel. Note that you must use make to create the channel:

ci := make(chan int)
cs := make(chan string)
cf := make(chan interface{})
Copy after login

The channel receives and sends data through the operator<-

ch <- v    // 发送v到channel ch.
v := <-ch  // 从ch中接收数据,并赋值给v
Copy after login

We apply these to our example :

package main

import "fmt"

func sum(a []int, c chan int) {
    total := 0
    for _, v := range a {
        total += v
    }
    c <- total  // send total to c
}

func main() {
    a := []int{7, 2, 8, -9, 4, 0}

    c := make(chan int)
    go sum(a[:len(a)/2], c)
    go sum(a[len(a)/2:], c)
    x, y := <-c, <-c  // receive from c

    fmt.Println(x, y, x + y)
}
Copy after login

By default, channel receiving and sending data are blocked unless the other end is ready, which makes Goroutines synchronization simpler without the need for explicit locks. The so-called blocking means that if you read (value := <-ch), it will be blocked until data is received. Second, any send (ch<-5) will be blocked until the data is read. Unbuffered channels are a great tool for synchronizing between multiple goroutines.

Buffered Channels

Above we introduced the default non-cache type channel, but Go also allows specifying channels The buffer size is simply how many elements the channel can store. ch:= make(chan bool, 4), creates a bool type channel that can store 4 elements. In this channel, the first 4 elements can be written without blocking. When the 5th element is written, the code will block until another goroutine reads some elements from the channel to make room.

ch := make(chan type, value)

value == 0 ! 无缓冲(阻塞)
value > 0 ! 缓冲(非阻塞,直到value 个元素)
Copy after login

我们看一下下面这个例子,你可以在自己本机测试一下,修改相应的value值

package main

import "fmt"

func main() {
    c := make(chan int, 2)//修改2为1就报错,修改2为3可以正常运行
    c <- 1
    c <- 2
    fmt.Println(<-c)
    fmt.Println(<-c)
}
    //修改为1报如下的错误:
    //fatal error: all goroutines are asleep - deadlock!
Copy after login

Range和Close

上面这个例子中,我们需要读取两次c,这样不是很方便,Go考虑到了这一点,所以也可以通过range,像操作slice或者map一样操作缓存类型的channel,请看下面的例子

package main

import (
    "fmt"
)

func fibonacci(n int, c chan int) {
    x, y := 1, 1
    for i := 0; i < n; i++ {
        c <- x
        x, y = y, x + y
    }
    close(c)
}

func main() {
    c := make(chan int, 10)
    go fibonacci(cap(c), c)
    for i := range c {
        fmt.Println(i)
    }
}
Copy after login

for i := range c能够不断的读取channel里面的数据,直到该channel被显式的关闭。上面代码我们看到可以显式的关闭channel,生产者通过内置函数close关闭channel。关闭channel之后就无法再发送任何数据了,在消费方可以通过语法v, ok := <-ch测试channel是否被关闭。如果ok返回false,那么说明channel已经没有任何数据并且已经被关闭。

记住应该在生产者的地方关闭channel,而不是消费的地方去关闭它,这样容易引起panic

另外记住一点的就是channel不像文件之类的,不需要经常去关闭,只有当你确实没有任何发送数据了,或者你想显式的结束range循环之类的

Select

我们上面介绍的都是只有一个channel的情况,那么如果存在多个channel的时候,我们该如何操作呢,Go里面提供了一个关键字select,通过select可以监听channel上的数据流动。

select默认是阻塞的,只有当监听的channel中有发送或接收可以进行时才会运行,当多个channel都准备好的时候,select是随机的选择一个执行的。

package main

import "fmt"

func fibonacci(c, quit chan int) {
    x, y := 1, 1
    for {
        select {
        case c <- x:
            x, y = y, x + y
        case <-quit:
            fmt.Println("quit")
            return
        }
    }
}

func main() {
    c := make(chan int)
    quit := make(chan int)
    go func() {
        for i := 0; i < 10; i++ {
            fmt.Println(<-c)
        }
        quit <- 0
    }()
    fibonacci(c, quit)
}
Copy after login

select里面还有default语法,select其实就是类似switch的功能,default就是当监听的channel都没有准备好的时候,默认执行的(select不再阻塞等待channel)。

select {
case i := <-c:
    // use i
default:
    // 当c阻塞的时候执行这里
}
Copy after login

超时

有时候会出现goroutine阻塞的情况,那么我们如何避免整个程序进入阻塞的情况呢?我们可以利用select来设置超时,通过如下的方式实现:

func main() {
    c := make(chan int)
    o := make(chan bool)
    go func() {
        for {
            select {
                case v := <- c:
                    println(v)
                case <- time.After(5 * time.Second):
                    println("timeout")
                    o <- true
                    break
            }
        }
    }()
    <- o
}
Copy after login

runtime goroutine

runtime包中有几个处理goroutine的函数:

  • Goexit

    退出当前执行的goroutine,但是defer函数还会继续调用

  • Gosched

    让出当前goroutine的执行权限,调度器安排其他等待的任务运行,并在下次某个时候从该位置恢复执行。

  • NumCPU

    返回 CPU 核数量

  • NumGoroutine

    返回正在执行和排队的任务总数

  • GOMAXPROCS

    用来设置可以并行计算的CPU核数的最大值,并返回之前的值。

【相关推荐:Go视频教程编程教学

The above is the detailed content of Is single-threading a feature of the Go language?. 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)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks 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)

How to safely read and write files using Golang? How to safely read and write files using Golang? Jun 06, 2024 pm 05:14 PM

Reading and writing files safely in Go is crucial. Guidelines include: Checking file permissions Closing files using defer Validating file paths Using context timeouts Following these guidelines ensures the security of your data and the robustness of your application.

How to configure connection pool for Golang database connection? How to configure connection pool for Golang database connection? Jun 06, 2024 am 11:21 AM

How to configure connection pooling for Go database connections? Use the DB type in the database/sql package to create a database connection; set MaxOpenConns to control the maximum number of concurrent connections; set MaxIdleConns to set the maximum number of idle connections; set ConnMaxLifetime to control the maximum life cycle of the connection.

Similarities and Differences between Golang and C++ Similarities and Differences between Golang and C++ Jun 05, 2024 pm 06:12 PM

Golang and C++ are garbage collected and manual memory management programming languages ​​respectively, with different syntax and type systems. Golang implements concurrent programming through Goroutine, and C++ implements it through threads. Golang memory management is simple, and C++ has stronger performance. In practical cases, Golang code is simpler and C++ has obvious performance advantages.

How steep is the learning curve of golang framework architecture? How steep is the learning curve of golang framework architecture? Jun 05, 2024 pm 06:59 PM

The learning curve of the Go framework architecture depends on familiarity with the Go language and back-end development and the complexity of the chosen framework: a good understanding of the basics of the Go language. It helps to have backend development experience. Frameworks that differ in complexity lead to differences in learning curves.

How to generate random elements from list in Golang? How to generate random elements from list in Golang? Jun 05, 2024 pm 04:28 PM

How to generate random elements of a list in Golang: use rand.Intn(len(list)) to generate a random integer within the length range of the list; use the integer as an index to get the corresponding element from the list.

Comparison of advantages and disadvantages of golang framework Comparison of advantages and disadvantages of golang framework Jun 05, 2024 pm 09:32 PM

The Go framework stands out due to its high performance and concurrency advantages, but it also has some disadvantages, such as being relatively new, having a small developer ecosystem, and lacking some features. Additionally, rapid changes and learning curves can vary from framework to framework. The Gin framework is a popular choice for building RESTful APIs due to its efficient routing, built-in JSON support, and powerful error handling.

What are the best practices for error handling in Golang framework? What are the best practices for error handling in Golang framework? Jun 05, 2024 pm 10:39 PM

Best practices: Create custom errors using well-defined error types (errors package) Provide more details Log errors appropriately Propagate errors correctly and avoid hiding or suppressing Wrap errors as needed to add context

What are the advantages of golang framework? What are the advantages of golang framework? Jun 06, 2024 am 10:26 AM

Advantages of the Golang Framework Golang is a high-performance, concurrent programming language that is particularly suitable for microservices and distributed systems. The Golang framework makes developing these applications easier by providing a set of ready-made components and tools. Here are some of the key advantages of the Golang framework: 1. High performance and concurrency: Golang itself is known for its high performance and concurrency. It uses goroutines, a lightweight threading mechanism that allows concurrent execution of code, thereby improving application throughput and responsiveness. 2. Modularity and reusability: Golang framework encourages modularity and reusable code. By breaking the application into independent modules, you can easily maintain and update the code

See all articles