Windows Internals - Chapter 4 Th

2018-01-12  本文已影响56人  我是柯南

线程

主要探讨Windows中线程和线程调度的基础数据结构和算法

进程和线程的关系

ThreadDiagram.png

创建线程

Windows API 创建线程 (Kernel32.dll)

HANDLE WINAPI CreateThread(
  _In_opt_  LPSECURITY_ATTRIBUTES  lpThreadAttributes,
  _In_      SIZE_T                 dwStackSize,
  _In_      LPTHREAD_START_ROUTINE lpStartAddress,
  _In_opt_  LPVOID                 lpParameter,
  _In_      DWORD                  dwCreationFlags,
  _Out_opt_ LPDWORD                lpThreadId
);

线程数据结构细节

Excutive Thread

The ETHREAD structure and the other structures it points to exist in the system
address space. The only exception is the thread environment block (TEB),
which exists in the process address space (similar to a PEB, because usermode
components need to access it).

image.png

Kernel Thread

image.png

查看线程状态


使用 Process Explorer (System internals)工具可以查看进程中线程的状态,以下是微信进程的线程状态


image.png

线程调度


Windows 实现的是基于 priority-driven preemptive 的线程调度系统,至少有一个最高优先级的线程一直在运行。

Priority levels

Windows 内部使用0-31共32级来定义线程优先级


image.png image.png

Quantum

线程运行的时间片,默认情况下,桌面系统默认值为2个时钟周期,服务器系统默认为12个时钟周期

Thread states

Dispatcher database

image.png

Priority boosts

Context switching

线程上线文数据和上下文切换的过程跟处理器架构密切相关,典型的上下文包括:

Direct Switch
windows 8 and server 2012 引入的一个优化机制

Scheduling Scenario

image.png image.png image.png

Idle threads

当CPU没有线程可执行时,就会执行idle线程,每个CPU都有自己的idle线程

Thread suspension

(Deep) freeze

让进程进入挂起状态,而且不能通过调用API ResumeThread来改变状态,比如当系统需要挂起UWP应用的时候(该应用进入后台),系统给该进程5秒钟的时间来处理应用状态的保存。

Deep freeze 实在上面的基础上再加一条约束,就是该应用中新创建的线程也不能运行。

这两个功能不是直接面向user mode的,是由 Process State Manager Sevice 负责处理的。

Thread selection

Heterogeneous Scheduling(bit.LITTLE)

Group-based scheduling

image.png

Dynamic fair share scheduling

Dynamic fair share scheduling (DFSS) is a mechanism that can be used to
fairly distribute CPU time among sessions running on a machine. It prevents
one session from potentially monopolizing the CPU if some threads running
under that session have a relatively high priority and run a lot. It’s enabled by
default on a Windows Server system that has the Remote Desktop role.

CPU rate limites

Dynamic processor addition and replacement

线程池

API

上一篇 下一篇

猜你喜欢

热点阅读