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

Waiting. A thread can enter the waiting state in several ways: a thread can voluntarily wait for an object to synchronize its execution, the operating system can wait on the thread’s behalf (such as to resolve a paging I/O), or an environment subsystem can direct the thread to suspend itself. When the thread’s wait ends, depending on the priority, the thread either begins running immediately or is moved back to the ready state.

Transition. A thread enters the transition state if it is ready for execution but its kernel stack is paged out of memory. Once its kernel stack is brought back into memory, the thread enters the ready state.

Terminated. When a thread finishes executing, it enters the terminated state. Once the thread is terminated, the executive thread object (the data structure in a nonpaged pool that describes the thread) might or might not be deallocated. (The object manager sets the policy regarding when to delete the object.)

Initialized. This state is used internally while a thread is being created.

Table 5-4 describes the state transitions for threads, and Figure 5-16 illustrates a simplified version. (The numeric values shown represent the value of the thread-state performance counter.) In the simplified version, the Ready, Standby, and Deferred Ready states are represented as one. This reflects the fact that the Standby and Deferred Ready states act as temporary placeholders for the scheduling routines. These states are almost always very short-lived; threads in these states always transition quickly to Ready, Running, or Waiting. More details on what happens at each transition are included later in this section.

Table 5-4. Thread States and Transitions

 

Init

Ready

Running

Standby

Terminated

Waiting

Transition

Deferred Ready 

Init

A thread becomes Initialized during the first few moments of its creation (KeStartThread).

Ready

A thread is added in the dispatcherready database of its ideal processor.

Running

Selected by KiSearchForNewThread

Picked up for execution by local CPU

Preemption after wait satisfaction

Standby

Selected by KiSelectNextThread

Selected by KiDeferredReadyThread for remote CPU

Terminated

Killed before PspInsertThread finished

Killed

A thread can kill only itself. It must be in the Running state before entering KeTerminateThread.

Waiting

Thread enters a wait

Only running threads can wait.

Transition

Kernel stack no longer resident

Only waiting threads can transition.

Deferred Ready

Last step in PspInsertThread

Affinity change

Thread becomes preempted (if old processor is no longer available)

Affinity change

Wait satisfaction (but no preemption)

Kernel stack swap-in completed

Figure 5-16. Simplified version of thread states and transitions

EXPERIMENT: Thread-Scheduling State Changes

You can watch thread-scheduling state changes with the Performance tool in Windows. This utility can be useful when you’re debugging a multithreaded application and you’re unsure about the state of the threads running in the process. To watch thread-scheduling state changes by using the Performance tool, follow these steps:

Run Notepad (Notepad.exe).

Start the Performance tool by selecting All Programs from the Start menu and then selecting Performance Monitor from the Administrative Tools menu. Click on the Performance Monitor entry under Monitoring Tools.

Select the chart view if you’re in some other view.

Right-click on the graph, and choose Properties.

Click on the Graph tab, and change the chart vertical scale maximum to 7. (As you’ll see from the explanation text for the performance counter, thread states are numbered from 0 through 7.) Click OK.

Click the Add button on the toolbar to bring up the Add Counters dialog box.

Select the Thread performance object, and then select the Thread State counter. Select the Show Description check box to see the definition of the values:

In the Instances box, select and type Notepad before clicking Search. Scroll down until you see the Notepad process (notepad/0); select it, and click the Add button.

Scroll back up in the Instances box to the Mmc process (the Microsoft Management Console process running the System Monitor), select all the threads (mmc/0, mmc/1, and so on), and add them to the chart by clicking the Add button. Before you click Add, you should see something like the dialog box that follows.

Now close the Add Counters dialog box by clicking OK.

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

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

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

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

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

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

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

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

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