Goroutine切换时CPU上下文会发生什么? [英] What happens with CPU context when Goroutines are switching?

查看:238
本文介绍了Goroutine切换时CPU上下文会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我正确理解goroutines如何在系统线程上工作 - 它们从一个队列中逐一运行。但这是否意味着每个goroutine都会加载它的上下文给CPU?如果是,系统线程和goroutines之间有什么区别?



最重要的问题是上下文切换的时间成本。这是正确的吗?



什么机制检测哪个数据是由哪个goroutine请求的?例如:我从goroutine A向DB发送请求,不等待响应,同时发生切换到下一个goroutine。系统如何理解请求来自A而不是来自B或C? Goroutines,memory and OS threads

Go有一个按需增长的分段堆栈。 Go运行时执行安排,而不是操作系统。运行时将多个goroutine复用到相对较少的实际操作系统线程中。

Goroutines switch cost



协同调度,当发生切换时,只需要保存/恢复3个寄存器 - 程序计数器,堆栈指针和DX。从操作系统的角度来看,Go程序就像事件驱动程序一样。



Goroutines和CPU



你不能直接控制运行时将创建的线程数。通过调用 runtime.GOMAXPROCS(n)来设置变量GOMAXPROCS,可以设置程序使用的处理器内核的数量。

程序计数器



和一个完全不同的故事

<在计算中,程序是计算机执行的一组特定的有序操作。指令是由程序给予计算机处理器的指令。在计算机内,地址是内存或存储中的特定位置。程序计数器寄存器是处理器使用的一小部分数据中的一个。



这是程序工作和通信的不同故事, t直接与goroutines主题相关。

来源:


If I correctly understand how goroutines work on top of system threads - they run from queue one by one. But does it mean that every goroutine loads\unloads it's context to CPU? If yes what's difference between system threads and goroutines?

The most significant problem is time-cost of context-switching. Is it correct?

What mechanism lays under detecting which data was requested by which goroutine? For example: I am sending request to DB from goroutine A and doesn't wait for response and at the same time occurred switch to a next goroutine. How system understands that a request came from A and not from B or C?

解决方案

Goroutines, memory and OS threads

Go has a segmented stack that grows as needed. Go runtime does the scheduling, not the OS. The runtime multiplexes the goroutines onto a relatively small number of real OS threads.

Goroutines switch cost

Goroutines are scheduled cooperatively and when a switch occurs, only 3 registers need to be saved/restored - Program Counter, Stack Pointer and DX. From the OS's perspective Go program behaves as event-driven program.

Goroutines and CPU

You cannot directly control the number of threads that the runtime will create. It is possible to set the number of processor cores used by the program by setting the variable GOMAXPROCS with a call to runtime.GOMAXPROCS(n).

Program Counter

and a completely different story

In computing, a program is a specific set of ordered operations for a computer to perform. An instruction is an order given to a computer processor by a program. Within a computer, an address is a specific location in memory or storage. A program counter register is one of a small set of data holding places that the processor uses.

This is different story how programs work and communicate with each other and it doesn't directly related to a goroutines topic.

Sources:

这篇关于Goroutine切换时CPU上下文会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆