Home  >  Article  >  Backend Development  >  What is the difference between threads and coroutines in golang

What is the difference between threads and coroutines in golang

青灯夜游
青灯夜游Original
2021-03-18 17:23:553148browse

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