Home >Backend Development >Golang >Is single-threading a feature of the Go language?

Is single-threading a feature of the Go language?

青灯夜游
青灯夜游Original
2023-01-06 11:17:193460browse

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)

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

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{})

The channel receives and sends data through the operator<-

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

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)
}

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 个元素)

我们看一下下面这个例子,你可以在自己本机测试一下,修改相应的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!

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)
    }
}

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)
}

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

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

超时

有时候会出现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
}

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:
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