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.
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 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 <p>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. </p><blockquote> <p>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. </p> <p>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 </p> </blockquote><p><a href="https://github.com/astaxie/build-web-application-with-golang/blob/master/zh/02.7.md#channels" rel="external nofollow" target="_blank"></a><strong><span style="font-size: 18px;">channels</span></strong></p><p>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: </p><pre class="brush:php;toolbar:false">ci := make(chan int) cs := make(chan string) cf := make(chan interface{})
The channel receives and sends data through the operator
ch <p>We apply these to our example :</p><pre class="brush:php;toolbar:false">package main import "fmt" func sum(a []int, c chan int) { total := 0 for _, v := range a { total += v } c <p>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 := </p><p><a href="https://github.com/astaxie/build-web-application-with-golang/blob/master/zh/02.7.md#buffered-channels" rel="external nofollow" target="_blank"></a><strong><span style="font-size: 18px;">Buffered Channels</span></strong></p><p> 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. </p><pre class="brush:php;toolbar:false">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 <p><a href="https://github.com/astaxie/build-web-application-with-golang/blob/master/zh/02.7.md#range%E5%92%8Cclose" rel="external nofollow" target="_blank"></a><strong><span style="font-size: 18px;">Range和Close</span></strong></p><p>上面这个例子中,我们需要读取两次c,这样不是很方便,Go考虑到了这一点,所以也可以通过range,像操作slice或者map一样操作缓存类型的channel,请看下面的例子</p><pre class="brush:php;toolbar:false">package main import ( "fmt" ) func fibonacci(n int, c chan int) { x, y := 1, 1 for i := 0; i <p><code>for i := range c</code>能够不断的读取channel里面的数据,直到该channel被显式的关闭。上面代码我们看到可以显式的关闭channel,生产者通过内置函数<code>close</code>关闭channel。关闭channel之后就无法再发送任何数据了,在消费方可以通过语法<code>v, ok := 测试channel是否被关闭。如果ok返回false,那么说明channel已经没有任何数据并且已经被关闭。</code></p><blockquote> <p>记住应该在生产者的地方关闭channel,而不是消费的地方去关闭它,这样容易引起panic</p> <p>另外记住一点的就是channel不像文件之类的,不需要经常去关闭,只有当你确实没有任何发送数据了,或者你想显式的结束range循环之类的</p> </blockquote><p><a href="https://github.com/astaxie/build-web-application-with-golang/blob/master/zh/02.7.md#select" rel="external nofollow" target="_blank"></a><strong><span style="font-size: 18px;">Select</span></strong></p><p>我们上面介绍的都是只有一个channel的情况,那么如果存在多个channel的时候,我们该如何操作呢,Go里面提供了一个关键字<code>select</code>,通过<code>select</code>可以监听channel上的数据流动。</p><p><code>select</code>默认是阻塞的,只有当监听的channel中有发送或接收可以进行时才会运行,当多个channel都准备好的时候,select是随机的选择一个执行的。</p><pre class="brush:php;toolbar:false">package main import "fmt" func fibonacci(c, quit chan int) { x, y := 1, 1 for { select { case c <p>在<code>select</code>里面还有default语法,<code>select</code>其实就是类似switch的功能,default就是当监听的channel都没有准备好的时候,默认执行的(select不再阻塞等待channel)。</p><pre class="brush:php;toolbar:false">select { case i := <p><a href="https://github.com/astaxie/build-web-application-with-golang/blob/master/zh/02.7.md#%E8%B6%85%E6%97%B6" rel="external nofollow" target="_blank"></a><strong><span style="font-size: 18px;">超时</span></strong></p><p>有时候会出现goroutine阻塞的情况,那么我们如何避免整个程序进入阻塞的情况呢?我们可以利用select来设置超时,通过如下的方式实现:</p><pre class="brush:php;toolbar:false">func main() { c := make(chan int) o := make(chan bool) go func() { for { select { case v := <p><a href="https://github.com/astaxie/build-web-application-with-golang/blob/master/zh/02.7.md#runtime-goroutine" rel="external nofollow" target="_blank"></a><strong><span style="font-size: 18px;">runtime goroutine</span></strong></p><p>runtime包中有几个处理goroutine的函数:</p>
-
Goexit
退出当前执行的goroutine,但是defer函数还会继续调用
-
Gosched
让出当前goroutine的执行权限,调度器安排其他等待的任务运行,并在下次某个时候从该位置恢复执行。
-
NumCPU
返回 CPU 核数量
-
NumGoroutine
返回正在执行和排队的任务总数
-
GOMAXPROCS
用来设置可以并行计算的CPU核数的最大值,并返回之前的值。
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!

Golangisidealforbuildingscalablesystemsduetoitsefficiencyandconcurrency,whilePythonexcelsinquickscriptinganddataanalysisduetoitssimplicityandvastecosystem.Golang'sdesignencouragesclean,readablecodeanditsgoroutinesenableefficientconcurrentoperations,t

Golang is better than C in concurrency, while C is better than Golang in raw speed. 1) Golang achieves efficient concurrency through goroutine and channel, which is suitable for handling a large number of concurrent tasks. 2)C Through compiler optimization and standard library, it provides high performance close to hardware, suitable for applications that require extreme optimization.

Reasons for choosing Golang include: 1) high concurrency performance, 2) static type system, 3) garbage collection mechanism, 4) rich standard libraries and ecosystems, which make it an ideal choice for developing efficient and reliable software.

Golang is suitable for rapid development and concurrent scenarios, and C is suitable for scenarios where extreme performance and low-level control are required. 1) Golang improves performance through garbage collection and concurrency mechanisms, and is suitable for high-concurrency Web service development. 2) C achieves the ultimate performance through manual memory management and compiler optimization, and is suitable for embedded system development.

Golang performs better in compilation time and concurrent processing, while C has more advantages in running speed and memory management. 1.Golang has fast compilation speed and is suitable for rapid development. 2.C runs fast and is suitable for performance-critical applications. 3. Golang is simple and efficient in concurrent processing, suitable for concurrent programming. 4.C Manual memory management provides higher performance, but increases development complexity.

Golang's application in web services and system programming is mainly reflected in its simplicity, efficiency and concurrency. 1) In web services, Golang supports the creation of high-performance web applications and APIs through powerful HTTP libraries and concurrent processing capabilities. 2) In system programming, Golang uses features close to hardware and compatibility with C language to be suitable for operating system development and embedded systems.

Golang and C have their own advantages and disadvantages in performance comparison: 1. Golang is suitable for high concurrency and rapid development, but garbage collection may affect performance; 2.C provides higher performance and hardware control, but has high development complexity. When making a choice, you need to consider project requirements and team skills in a comprehensive way.

Golang is suitable for high-performance and concurrent programming scenarios, while Python is suitable for rapid development and data processing. 1.Golang emphasizes simplicity and efficiency, and is suitable for back-end services and microservices. 2. Python is known for its concise syntax and rich libraries, suitable for data science and machine learning.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version
Useful JavaScript development tools