search
HomeBackend DevelopmentGolangWhat 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.

What is the difference between threads and coroutines in golang

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!

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
Choosing Between Golang and Python: The Right Fit for Your ProjectChoosing Between Golang and Python: The Right Fit for Your ProjectApr 19, 2025 am 12:21 AM

Golangisidealforperformance-criticalapplicationsandconcurrentprogramming,whilePythonexcelsindatascience,rapidprototyping,andversatility.1)Forhigh-performanceneeds,chooseGolangduetoitsefficiencyandconcurrencyfeatures.2)Fordata-drivenprojects,Pythonisp

Golang: Concurrency and Performance in ActionGolang: Concurrency and Performance in ActionApr 19, 2025 am 12:20 AM

Golang achieves efficient concurrency through goroutine and channel: 1.goroutine is a lightweight thread, started with the go keyword; 2.channel is used for secure communication between goroutines to avoid race conditions; 3. The usage example shows basic and advanced usage; 4. Common errors include deadlocks and data competition, which can be detected by gorun-race; 5. Performance optimization suggests reducing the use of channel, reasonably setting the number of goroutines, and using sync.Pool to manage memory.

Golang vs. Python: Which Language Should You Learn?Golang vs. Python: Which Language Should You Learn?Apr 19, 2025 am 12:20 AM

Golang is more suitable for system programming and high concurrency applications, while Python is more suitable for data science and rapid development. 1) Golang is developed by Google, statically typing, emphasizing simplicity and efficiency, and is suitable for high concurrency scenarios. 2) Python is created by Guidovan Rossum, dynamically typed, concise syntax, wide application, suitable for beginners and data processing.

Golang vs. Python: Performance and ScalabilityGolang vs. Python: Performance and ScalabilityApr 19, 2025 am 12:18 AM

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Golang vs. Other Languages: A ComparisonGolang vs. Other Languages: A ComparisonApr 19, 2025 am 12:11 AM

Go language has unique advantages in concurrent programming, performance, learning curve, etc.: 1. Concurrent programming is realized through goroutine and channel, which is lightweight and efficient. 2. The compilation speed is fast and the operation performance is close to that of C language. 3. The grammar is concise, the learning curve is smooth, and the ecosystem is rich.

Golang and Python: Understanding the DifferencesGolang and Python: Understanding the DifferencesApr 18, 2025 am 12:21 AM

The main differences between Golang and Python are concurrency models, type systems, performance and execution speed. 1. Golang uses the CSP model, which is suitable for high concurrent tasks; Python relies on multi-threading and GIL, which is suitable for I/O-intensive tasks. 2. Golang is a static type, and Python is a dynamic type. 3. Golang compiled language execution speed is fast, and Python interpreted language development is fast.

Golang vs. C  : Assessing the Speed DifferenceGolang vs. C : Assessing the Speed DifferenceApr 18, 2025 am 12:20 AM

Golang is usually slower than C, but Golang has more advantages in concurrent programming and development efficiency: 1) Golang's garbage collection and concurrency model makes it perform well in high concurrency scenarios; 2) C obtains higher performance through manual memory management and hardware optimization, but has higher development complexity.

Golang: A Key Language for Cloud Computing and DevOpsGolang: A Key Language for Cloud Computing and DevOpsApr 18, 2025 am 12:18 AM

Golang is widely used in cloud computing and DevOps, and its advantages lie in simplicity, efficiency and concurrent programming capabilities. 1) In cloud computing, Golang efficiently handles concurrent requests through goroutine and channel mechanisms. 2) In DevOps, Golang's fast compilation and cross-platform features make it the first choice for automation tools.

See all articles

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

Video Face Swap

Video Face Swap

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

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)