Читаем Windows® Internals, Sixth Edition, Part 1 полностью

You can view the list of ready threads with the kernel debugger !ready command. This command displays the thread or list of threads that are ready to run at each priority level. In the following example, generated on a 32-bit machine with a dual-core processor, two threads are ready to run at priority 8 on the first logical processor, and one thread at priority 10, two threads at priority 9, and three threads at priority 8 are ready to run on the second logical processor. Determining which of these threads get to run on their respective processor is a simple matter of picking the first thread on top of the highest priority queue (thread 857d9030 for logical processor 0, and thread 857c0030 for logical processor 1), but why the queues contain the threads they do is a complex result at the end of several algorithms that the scheduler uses. We will cover this topic later in this section.kd> !ready Processor 0: Ready Threads at priority 8 THREAD 857d9030 Cid 0ec8.0e30 Teb: 7ffdd000 Win32Thread: 00000000 READY THREAD 855c8300 Cid 0ec8.0eb0 Teb: 7ff9c000 Win32Thread: 00000000 READY Processor 1: Ready Threads at priority 10 THREAD 857c0030 Cid 04c8.0378 Teb: 7ffdf000 Win32Thread: fef7f8c0 READY Processor 1: Ready Threads at priority 9 THREAD 87fc86f0 Cid 0ec8.04c0 Teb: 7ffd3000 Win32Thread: 00000000 READY THREAD 88696700 Cid 0ec8.0ce8 Teb: 7ffa0000 Win32Thread: 00000000 READY Processor 1: Ready Threads at priority 8 THREAD 856e5520 Cid 0ec8.0228 Teb: 7ff98000 Win32Thread: 00000000 READY THREAD 85609d78 Cid 0ec8.09b0 Teb: 7ffd9000 Win32Thread: 00000000 READY THREAD 85fdeb78 Cid 0ec8.0218 Teb: 7ff72000 Win32Thread: 00000000 READY

After a thread is selected to run, it runs for an amount of time called a quantum. A quantum is the length of time a thread is allowed to run before another thread at the same priority level is given a turn to run. Quantum values can vary from system to system and process to process for any of three reasons:

System configuration settings (long or short quantums, variable or fixed quantums, and priority separation)

Foreground or background status of the process

Use of the job object to alter the quantum

These details are explained in more details in the Quantum section later in the chapter, as well as in the Job Objects section).

A thread might not get to complete its quantum, however, because Windows implements a preemptive scheduler: if another thread with a higher priority becomes ready to run, the currently running thread might be preempted before finishing its time slice. In fact, a thread can be selected to run next and be preempted before even beginning its quantum!

The Windows scheduling code is implemented in the kernel. There’s no single “scheduler” module or routine, however—the code is spread throughout the kernel in which scheduling-related events occur. The routines that perform these duties are collectively called the kernel’s dispatcher. The following events might require thread dispatching:

A thread becomes ready to execute—for example, a thread has been newly created or has just been released from the wait state.

A thread leaves the running state because its time quantum ends, it terminates, it yields execution, or it enters a wait state.

A thread’s priority changes, either because of a system service call or because Windows itself changes the priority value.

A thread’s processor affinity changes so that it will no longer run on the processor on which it was running.

At each of these junctions, Windows must determine which thread should run next on the logical processor that was running the thread, if applicable, or on which logical processor the thread should now run on. After a logical processor has selected a new thread to run, it eventually performs a context switch to it. A context switch is the procedure of saving the volatile processor state associated with a running thread, loading another thread’s volatile state, and starting the new thread’s execution.

As already noted, Windows schedules at the thread granularity. This approach makes sense when you consider that processes don’t run but only provide resources and a context in which their threads run. Because scheduling decisions are made strictly on a thread basis, no consideration is given to what process the thread belongs to. For example, if process A has 10 runnable threads, process B has 2 runnable threads, and all 12 threads are at the same priority, each thread would theoretically receive one-twelfth of the CPU time—Windows wouldn’t give 50 percent of the CPU to process A and 50 percent to process B.


Priority Levels

To understand the thread-scheduling algorithms, one must first understand the priority levels that Windows uses. As illustrated in Figure 5-14, internally Windows uses 32 priority levels, ranging from 0 through 31. These values divide up as follows:

Sixteen real-time levels (16 through 31)

Перейти на страницу:

Похожие книги

Самоучитель UML
Самоучитель UML

Самоучитель UMLПервое издание.В книге рассматриваются основы UML – унифицированного языка моделирования для описания, визуализации и документирования объектно-ориентированных систем и бизнес-процессов в ходе разработки программных приложений. Подробно описываются базовые понятия UML, необходимые для построения объектно-ориентированной модели системы с использованием графической нотации. Изложение сопровождается примерами разработки отдельных диаграмм, которые необходимы для представления информационной модели системы. Цель книги – помочь программистам освоить новую методологию разработки корпоративных программных приложений для последующего применения полученных знаний с использованием соответствующих CASE-инструментов.

Александр Васильевич Леоненков , Александр Леоненков

Зарубежная компьютерная, околокомпьютерная литература / Программирование / Прочая компьютерная литература / Книги по IT
Об интеллекте
Об интеллекте

В книге "Об интеллекте" Джефф Хокинс представляет революционную теорию на стыке нейробиологии, психологии и кибернетики и описывающую систему "память-предсказание" как основу человеческого интеллекта. Автор отмечает, что все предшествующие попытки создания разумных машин провалились из-за фундаментальной ошибки разработчиков, стремившихся воссоздать человеческое поведение, но не учитывавших природу биологического разума. Джефф Хокинс предполагает, что идеи, сформулированные им в книге "Об интеллекте", лягут в основу создания истинного искусственного интеллекта - не копирующего, а превосходящего человеческий разум. Кроме этого книга содержит рассуждения о последствиях и возможностях создания разумных машин, взгляды автора на природу и отличительные особенности человеческого интеллекта.Книга рекомендуется всем, кого интересует устройство человеческого мозга и принципы его функционирования, а также тем, кто занимается проблемами разработки искусственного интеллекта.

Джефф Хокинс , Джеф Хокинс , Сандра Блейксли , Сандра Блэйксли

Зарубежная компьютерная, околокомпьютерная литература / Технические науки / Прочая компьютерная литература / Образование и наука / Книги по IT