线程上下文和同步上下文

Thread Context and Synchronization Context

我看到在有关线程的文档中使用术语 Thread ContextSynchronization Context。他们指的是同一件事吗? 这是微软对线程上下文的定义:

The thread context includes all the information the thread needs to seamlessly resume execution, including the thread's set of CPU registers and stack, in the address space of the thread's host process.

据我了解,线程池中的线程共享相同的同步上下文。这是否意味着它们具有相同的线程上下文?

同步上下文和线程上下文是两个截然不同的东西。同步上下文是一种可以将工作单元排队到上下文(主要是不同线程)的方法。 Here 是引用。

One aspect of SynchronizationContext is that it provides a way to queue a unit of work to a context. Note that this unit of work is queued to a context rather than a specific thread. This distinction is important, because many implementations of SynchronizationContext aren’t based on a single, specific thread.

同步上下文很有用的典型示例是 GUI 应用程序,例如 WinForms 或 WPF 应用程序。在 WinForms 和 WPF 中,只有一个 UI 线程可以更新 UI 元素(文本框、复选框等)。如果您尝试从另一个非 UI 线程更改文本框的内容,则更改不会发生或可能会抛出异常(取决于 UI 框架)。所以在这样的应用程序中,工作非UI线程需要将对UI元素的所有更改安排到UI线程。这就是同步上下文提供的。它允许您 post 一个工作单元(某些方法的执行)到不同的上下文 - 在这种情况下是 UI 线程。

另一方面,线程上下文是一个结构,其中包含 OS 执行线程代码所需的所有信息。如果 OS 需要将执行从一个线程更改为另一个线程,它会执行称为上下文切换的操作。在上下文切换中,当前在 CPU 上 运行ning 的线程被 OS 冻结,并且所有 CPU 寄存器的当前状态存储到线程上下文结构中冻结的线程。 Here is the actual thread context structure on Windows OS and here x64 Windows。当所有 CPU 寄存器的内容被移动到冻结线程的线程上下文时,OS 找到另一个(最优先的)线程必须 运行 它的代码,并移动其线程上下文结构的内容到 CPU 寄存器。此后,上下文切换结束,CPU 可以执行最前面的线程的代码,直到发生另一个上下文切换。

所以同步上下文和线程上下文是两个截然不同的概念。线程上下文是允许 OS 在线程之间切换的低级结构,而同步上下文是一种简化将工作项发送到不同上下文(主要是不同线程)的机制。