What is the difference between threads and coroutines in golang
Difference: The data in the thread is stored in the kernel-mode memory space; while the data in the coroutine is stored in the user-mode memory space provided by the thread. The task scheduling of threads is implemented by the kernel, and the preemption method relies on various locks; the task scheduling of coroutines is implemented by a specific scheduler implemented in user mode.
The operating environment of this tutorial: windows10 system, GO 1.11.2, thinkpad t480 computer.
Coroutine
Coroutine, the English name is Coroutine. But in Go language, the English name of coroutine is: gorutine. It is often used for multitasking, i.e. concurrent jobs. That's right, it's the multi-threaded job.
Although in Go, we do not need to directly write code such as threads to perform concurrency, Go's coroutines rely on threads.
Let’s take a look at their differences.
Basic introduction to threads, please search for articles online here, because there are many excellent introduction articles about threads.
Characteristics of coroutines
Here we first directly list the characteristics of threads, and then analyze them from examples.
Multiple coroutines can be managed by one or more threads, The scheduling of coroutines occurs in the thread in which they are located.
can be scheduled. Scheduling strategy is defined by the application layer code and can be highly customized.
High execution efficiency.
takes up less memory.
The above 1 and 2 points
我们来看一个例子: func TestGorutine(t *testing.T) { runtime.GOMAXPROCS(1) // 指定最大 P 为 1,从而管理协程最多的线程为 1 个 wg := sync.WaitGroup{} // 控制等待所有协程都执行完再退出程序 wg.Add(2) // 运行一个协程 go func() { fmt.Println(1) fmt.Println(2) fmt.Println(3) wg.Done() }() // 运行第二个协程 go func() { fmt.Println(65) fmt.Println(66) // 设置个睡眠,让该协程执行超时而被挂起,引起超时调度 time.Sleep(time.Second) fmt.Println(67) wg.Done() }() wg.Wait()}
The above code snippet ran After running the two coroutines, the order of the observed output is staggered . It may be:
656612367
means that during the execution of coroutine A, you can interrupt at any time to execute coroutine B. Coroutine B may also be interrupted during the execution process. Execute coroutine A.
It seems that the running of coroutine A and coroutine B is like thread switching, but please note that A and B here are both running in the same thread. Their scheduling is not thread switching, but pure application-state coroutine scheduling.
Regarding the above code, why do you need to specify the following two lines of code?
runtime.GOMAXPROCS(1)time.Sleep(time.Second)
This requires you to take a look at the basics of Go's coroutine scheduling. Please read my other previous scheduling analysis article:
Go's coroutine scheduling mechanism
If not Set runtime.GOMAXPROCS(1), then the program will start the corresponding number of P according to the number of CPU cores of the operating system, resulting in the startup of multiple M, that is, threads. Then the coroutines in our program will be assigned to different threads. For demonstration purposes, the number is set to 1 so that they are all assigned to the same thread and stored in the thread's coroutine queue, waiting to be executed or scheduled.
The 3 and 4 points in the coroutine characteristics.
3. High execution efficiency.
4. Occupies little memory.
Because the scheduling switching of the coroutine is not a thread switching, but is controlled by the program itself, therefore, There is no overhead of thread switching, compared with multi-threading, the number of threads The more there are, the more obvious the performance advantages of coroutines are. Scheduling occurs in application mode rather than kernel mode.
The memory cost is to use the memory of the thread where it is located, which means that the thread's memory can be used by multiple coroutines.
Secondly, the scheduling of coroutines does not require a multi-thread lock mechanism, because there is only one thread, and there is no conflict of writing variables at the same time, so the execution efficiency is higher than that of multi-threads Much higher.
Overall comparison of coroutines and threads
Comparison points | Threads | Coroutine |
---|---|---|
Data storage | Kernel state memory space | It is generally the user state memory space provided by the thread |
Switching operation | The operation is finally completed at the kernel layer. The application layer needs to call the syscall underlying function provided by the kernel layer | The application layer uses code to perform simple on-site operations Just save and restore |
Task scheduling | Is implemented by the kernel, preemption mode, relies on various locks | Specific scheduling implemented by user mode device to proceed. For example, the go coroutine scheduler |
Voice support | Most programming languages | Some languages: Lua, Go, Python... |
Implementation specifications | Implementation in accordance with modern operating system specifications | There is no unified specification. It is implemented by developers at the application layer and is highly customized. For example, it only supports single-threaded threads. Different scheduling strategies, etc. |
Recommended learning: Golang tutorial
The above is the detailed content of What is the difference between threads and coroutines in golang. For more information, please follow other related articles on the PHP Chinese website!

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics



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

The difference between the GoLang framework and the Go framework is reflected in the internal architecture and external features. The GoLang framework is based on the Go standard library and extends its functionality, while the Go framework consists of independent libraries to achieve specific purposes. The GoLang framework is more flexible and the Go framework is easier to use. The GoLang framework has a slight advantage in performance, and the Go framework is more scalable. Case: gin-gonic (Go framework) is used to build REST API, while Echo (GoLang framework) is used to build web applications.

JSON data can be saved into a MySQL database by using the gjson library or the json.Unmarshal function. The gjson library provides convenience methods to parse JSON fields, and the json.Unmarshal function requires a target type pointer to unmarshal JSON data. Both methods require preparing SQL statements and performing insert operations to persist the data into the database.

The FindStringSubmatch function finds the first substring matched by a regular expression: the function returns a slice containing the matching substring, with the first element being the entire matched string and subsequent elements being individual substrings. Code example: regexp.FindStringSubmatch(text,pattern) returns a slice of matching substrings. Practical case: It can be used to match the domain name in the email address, for example: email:="user@example.com", pattern:=@([^\s]+)$ to get the domain name match[1].

Backend learning path: The exploration journey from front-end to back-end As a back-end beginner who transforms from front-end development, you already have the foundation of nodejs,...

Using predefined time zones in Go includes the following steps: Import the "time" package. Load a specific time zone through the LoadLocation function. Use the loaded time zone in operations such as creating Time objects, parsing time strings, and performing date and time conversions. Compare dates using different time zones to illustrate the application of the predefined time zone feature.

Go framework development FAQ: Framework selection: Depends on application requirements and developer preferences, such as Gin (API), Echo (extensible), Beego (ORM), Iris (performance). Installation and use: Use the gomod command to install, import the framework and use it. Database interaction: Use ORM libraries, such as gorm, to establish database connections and operations. Authentication and authorization: Use session management and authentication middleware such as gin-contrib/sessions. Practical case: Use the Gin framework to build a simple blog API that provides POST, GET and other functions.
