Thread count windows что это

Windows Threads

Общая схема использования потоков Windows Threads

Для создания дополнительного потока необходимо вызывать функцию CreateThread , в качестве аргументов этой функции передаются приоритет запускаемого потока, функция, которую он будет исполнять, и ее аргументы. Ниже представлен пример создания дополнительного потока:

Для создания нескольких дочерних потоков необходимо несколько раз вызвать метод CreateThread

При разработке параллельных приложений на основе явного использования потоков операционной системы Windows важным аспектом является организация согласованного доступа к ресурсам, которые используются несколькими потоками, будь это общие переменные или участки памяти. Такие ресурсы называются общими или разделяемыми. При наличии нескольких потоков необходимо осуществлять синхронизацию их работы – это можно сделать с помощью таких механизмов операционной системы как критические секции, мьютексы, семафоры, события и другие.

Важные положительные моменты технологии Windows threads:

  • Разработка параллельных приложений на основе данной технологии позволяет явно управлять созданием и завершением потоков. Таким образом, обеспечивается контроль за началом и окончанием работы потоков.
  • Явное задание начальных данных и способов их обработки потоками.
  • Возможность достижения более высокого ускорения по сравнению с использованием технологии OpenMP.

Одним из недостатков данной технологии является необходимость реализации согласованного доступа к общим ресурсам и синхронизации выполнения потоков с помощью системных или пользовательских механизмов.

Controlling Processes and Threads

When you are performing user-mode debugging, you activate, display, freeze, unfreeze, suspend, and unsuspend processes and threads.

The current or active process is the process that is currently being debugged. Similarly, the current or active thread is the thread that the debugger is currently controlling. The actions of many debugger commands are determined by the identity of the current process and thread. The current process also determines the virtual address mappings that the debugger uses.

When debugging begins, the current process is the one that the debugger is attached to or that caused the exception that broke into the debugger. Similarly, the current thread is the one that was active when the debugger attached to the process or that caused the exception. However, you can use the debugger to change the current process and thread and to freeze or unfreeze individual threads.

In kernel-mode debugging, processes and threads are not controlled by the methods that are described in this section. For more information about how processes and threads are manipulated in kernel mode, see Changing Contexts.

Displaying Processes and Threads

To display process and thread information, you can use the following methods:

Setting the Current Process and Thread

To change the current process or thread, you can use the following methods:

Freezing and Suspending Threads

The debugger can change the execution of a thread by suspending the thread or by freezing the thread. These two actions have somewhat different effects.

Each thread has a suspend count that is associated with it. If this count is one or larger, the system does not run the thread. If the count is zero or lower, the system runs the thread when appropriate.

Typically, each thread has a suspend count of zero. When the debugger attaches to a process, it increments the suspend counts of all threads in that process by one. If the debugger detaches from the process, it decrements all suspend counts by one. When the debugger executes the process, it temporarily decrements all suspend counts by one.

You can control the suspend count of any thread from the debugger by using the following methods:

n (Suspend Thread) command increments the specified thread’s suspend count by one.

m (Resume Thread) command decrements the specified thread’s suspend count by one.

The most common use for these commands is to raise a specific thread’s suspend count from one to two. When the debugger executes or detaches from the process, the thread then has a suspend count of one and remains suspended, even if other threads in the process are executing.

You can suspend threads even when you are performing noninvasive debugging.

The debugger can also freeze a thread. This action is similar to suspending the thread in some ways. However, «frozen» is only a debugger setting. Nothing in the Windows operating system recognizes that anything is different about this thread.

By default, all threads are unfrozen. When the debugger causes a process to execute, threads that are frozen do not execute. However, if the debugger detaches from the process, all threads unfreeze.

To freeze and unfreeze individual threads, you can use the following methods:

f (Freeze Thread) command freezes the specified thread.

u (Unfreeze Thread) command unfreezes the specified thread.

In any event, threads that belong to the target process never execute when the debugger has broken into the target. The suspend count of a thread affects the thread’s behavior only when the debugger executes the process or detaches. The frozen status affects the thread’s behavior only when the debugger executes the process.

Threads and Processes in Other Commands

You can add thread specifiers or process specifiers before many other commands. For more information, see the individual command topics.

You can add the

e (Thread-Specific Command) qualifier before many commands and extension commands. This qualifier causes the command to be executed with respect to the specified thread. This qualifier is especially useful if you want to apply a command to more than one thread. For example, the following command repeats the !gle extension command for every thread that is being debugged.

Multiple Systems

The debugger can attach to multiple targets at the same time. When these processes include dump files or include live targets on more than one computer, the debugger references a system, process, and thread for each action. For more information about this kind of debugging, see Debugging Multiple Targets.

Пошаговое руководство. Отладка многопоточного приложения с помощью окна «Потоки» (C#, Visual Basic, C++) Walkthrough: Debug a multithreaded app using the Threads window (C#, Visual Basic, C++)

Несколько элементов пользовательского интерфейса Visual Studio позволяют отлаживать многопоточные приложения. Several Visual Studio user interface elements help you debug multithreaded apps. В этой статье представлены функции многопотоковой отладки в окне редактора кода, на панели инструментов Место отладки и в окне Потоки. This article introduces multithreaded debugging features in the code editor window, Debug Location toolbar, and Threads window. Дополнительные сведения о других средствах отладки многопоточных приложений см. в разделе Начало отладки многопоточных приложений. For information about other tools for debugging multithreaded apps, see Get started debugging multithreaded apps.

Выполнение этого учебника занимает всего несколько минут, в ходе которых вы ознакомитесь с основами отладки многопоточных приложений. Completing this tutorial takes only a few minutes, and familiarizes you with the basics of debugging multithreaded apps.

Создание проекта многопоточного приложения Create a multithreaded app project

Создайте следующий проект многопоточного приложения для использования в этом учебнике: Create the following multithreaded app project to use in this tutorial:

Откройте Visual Studio и создайте новый проект. Open Visual Studio and create a new project.

Если окно запуска не открыто, выберите Файл > Окно запуска. If the start window is not open, choose File > Start Window.

На начальном экране выберите Создать проект. On the start window, choose Create a new project.

В поле поиска окна Создание проекта введите консоль. On the Create a new project window, enter or type console in the search box. Затем выберите C# или C++ в списке языков и Windows в списке платформ. Next, choose C# or C++ from the Language list, and then choose Windows from the Platform list.

Применив фильтры по языку и платформе, выберите шаблон Консольное приложение для .NET Core или C++ и щелкните Далее. After you apply the language and platform filters, choose the Console App for .NET Core or for C++, and then choose Next.

Если нужный шаблон проекта отсутствует, перейдите в меню Сервис > Получить средства и компоненты. , после чего запустится Visual Studio Installer. If you don’t see the correct template, go to Tools > Get Tools and Features. , which opens the Visual Studio Installer. Выберите рабочую нагрузку Кроссплатформенная разработка .NET Core или Разработка классических приложений на C++ и щелкните Изменить. Choose the .NET Core cross-platform development or Desktop development with C++ workload, then choose Modify.

В поле Имя проекта окна Настроить новый проект введите MyThreadWalkthroughApp. In the Configure your new project window, type or enter MyThreadWalkthroughApp in the Project name box. Затем щелкните Далее или Создать в зависимости от того, какой вариант доступен. Then, choose Next or Create, whichever option is available.

Для .NET Core выберите рекомендуемую версию целевой платформы (.NET Core 3.1) или .NET 5 и щелкните Создать. For .NET Core, choose either the recommended target framework (.NET Core 3.1) or .NET 5, and then choose Create.

В верхней строке меню последовательно выберите Файл > Создать > Проект. From the top menu bar, choose File > New > Project. В левой области диалогового окна Создание проекта выберите следующие элементы. In the left pane of the New project dialog box, choose the following:

  • Для приложения C# в разделе Visual C# выберите Рабочий стол Windows, а затем в средней области выберите Консольное приложение (.NET Framework) . For a C# app, under Visual C#, choose Windows Desktop, and then in the middle pane choose Console App (.NET Framework).
  • Для приложения C++ в разделе Visual C++ выберите Рабочий стол Windows, а затем выберите Консольное приложение Windows. For a C++ app, under Visual C++, choose Windows Desktop,, and then choose Windows Console Application.

Если вы не видите шаблон Консольное приложение (.NET Framework) или (для C++) Консольное приложение, выберите Сервис > Получить средства и компоненты, после чего запустится Visual Studio Installer. If you don’t see the Console App (.NET Framework) or, for C++, the Console App project template, go to Tools > Get Tools and Features. , which opens the Visual Studio Installer. Выберите рабочую нагрузку Разработка классических приложений .NET или Разработка классических приложений на C++ , а затем нажмите кнопку Изменить. Choose the .NET desktop development or Desktop development with C++ workload, then choose Modify.

Введите имя, например MyThreadWalkthroughApp, и нажмите ОК. Then, type a name like MyThreadWalkthroughApp and click OK.

Нажмите кнопку ОК. Select OK.

Появится новый проект консольного приложения. A new console project appears. Когда проект будет создан, откроется файл исходного кода. After the project has been created, a source file appears. В зависимости от выбранного языка файл исходного кода может называться Program.cs, MyThreadWalkthroughApp.cpp или Module1.vb. Depending on the language you have chosen, the source file might be called Program.cs, MyThreadWalkthroughApp.cpp, or Module1.vb.

Замените код в исходном файле на пример кода C# или C++ из раздела Начало отладки многопоточных приложений. Replace the code in the source file with the C# or C++ example code from Get started debugging multithreaded apps.

Нажмите Файл > Сохранить все. Select File > Save All.

Начать отладку Start debugging

Найдите следующие строки в исходном коде: Find the following lines in the source code:

Установите точку останова на строке Console.WriteLine(); , щелкнув в левом поле или выбрав строку и нажав клавишу F9. Set a breakpoint on the Console.WriteLine(); line by clicking in the left gutter, or selecting the line and pressing F9.

Точка останова отображается как красный кружок в левом поле рядом со строкой кода. The breakpoint appears as a red circle in the left gutter next to the code line.

Выберите Отладка > Начать отладку или нажмите клавишу F5. Select Debug > Start Debugging, or press F5.

Приложение запускается в режиме отладки и останавливается в точке останова. The app starts in debug mode, and pauses at the breakpoint.

В режиме приостановки откройте окно Потоки, выбрав Отладка > Windows > Потоки. While in break mode, open the Threads window by selecting Debug > Windows > Threads. Чтобы открыть или просмотреть окно Потоки и другие окна отладки, необходимо находиться в сеансе отладки. You must be in a debugging session to open or see the Threads and other debugging windows.

Проверка маркеров потоков Examine thread markers

В исходном коде найдите строку Console.WriteLine(); . In the source code, locate the Console.WriteLine(); line.

  1. Щелкните правой кнопкой мыши в окне Потоки и в меню выберите Показывать потоки в источнике. Right-click in the Threads window, and select Show Threads in Sourcefrom the menu.

В поле рядом со строкой исходного кода будет отображаться значок маркера потока . The gutter next to the source code line now displays a thread marker icon . маркер потока указывает, что некий поток остановлен в этом месте. The thread marker indicates that a thread is stopped at this location. Если в расположении больше одного остановленного потока, появляется значок . If there is more than one stopped thread at the location, the icon appears.

Наведите указатель мыши на маркер потока. Hover the pointer over the thread marker. Подсказка сообщает имя и идентификационный номер каждого остановившегося тут потока. A DataTip appears, showing the name and thread ID number for the stopped thread or threads. Имена потоков могут иметь значение . The thread names may be .

Чтобы различать безымянные потоки, их можно переименовать в окне Потоки. To help identify nameless threads, you can rename them in the Threads window. Щелкните поток правой кнопкой мыши и выберите пункт Переименовать. Right-click the thread and select Rename.

Щелкните маркер потока в исходном коде правой кнопкой мыши, чтобы просмотреть доступные параметры в контекстном меню. Right-click the thread marker in the source code to see the available options on the shortcut menu.

Установка и снятие отметки для потока Flag and unflag threads

Вы можете помечать требующие внимания потоки, чтобы следить за ними. You can flag threads to keep track of threads you want to pay special attention to.

Устанавливайте и снимайте метки потоков в редакторе исходного кода или в окне Потоки. Flag and unflag threads from the source code editor or from the Threads window. Выберите, следует ли отображать только помеченные потоки или все потоки, в окне Место отладки или Потоки. Choose whether to display only flagged threads, or all threads, from the Debug Location or Threads window toolbars. Выбор, сделанный из любого расположения, влияет на все расположения. Selections made from any location affect all locations.

Установка и снятие метки для потоков в исходном коде Flag and unflag threads in source code

Чтобы открыть панель инструментов Место отладки, выберите Вид > Панели инструментов > Место отладки. Open the Debug Location toolbar by selecting View > Toolbars > Debug Location. Можно также щелкнуть правой кнопкой мыши в области панели инструментов и выбрать Место отладки. You can also right-click in the toolbar area and select Debug Location.

Панель инструментов Место отладки содержит три поля: Процесс, Поток и Кадр стека. The Debug Location toolbar has three fields: Process, Thread, and Stack Frame. Откройте раскрывающийся список Поток и обратите внимание на количество потоков. Drop down the Thread list, and note how many threads there are. В списке Поток выполняющийся в данный момент поток помечается символом > . In the Thread list, the currently executing thread is marked by a > symbol.

В окне исходного кода наведите указатель мыши на значок маркера потока в поле и выберите значок флага (или один из пустых значков флагов) в подсказке. In the source code window, hover over a thread marker icon in the gutter and select the flag icon (or one of the empty flag icons) in the DataTip. Значок флага становится красным. The flag icon turns red.

Можно также щелкнуть правой кнопкой мыши значок маркера потока, навести курсор на Флаг, а затем выбрать поток для пометки в контекстном меню. You can also right-click a thread marker icon, point to Flag, and then select a thread to flag from the shortcut menu.

На панели инструментов Место отладки нажмите значок Показывать только помеченные потоки справа от поля Поток. On the Debug Location toolbar, select the Show Only Flagged Threads icon , to the right of the Thread field. Значок неактивен, если ни один поток не помечен. The icon is grayed out unless one or more threads are flagged.

Теперь в раскрывающемся списке Поток на панели инструментов отображается только помеченный поток. Only the flagged thread now appears in the Thread dropdown in the toolbar. Нажмите кнопку Показывать только помеченные потоки еще раз, чтобы снова отображались все потоки. To show all threads again, select the Show Only Flagged Threads icon again.

Пометив несколько потоков, поместите курсор в редакторе кода, щелкните правой кнопкой мыши и выберите Запустить помеченные потоки до курсора. After you have flagged some threads, you can place your cursor in the code editor, right-click, and select Run Flagged Threads to Cursor. Обязательно выберите код, которого достигнут все потоки. Make sure to choose code that all flagged threads will reach. Запустить помеченные потоки до курсора — потоки будут приостановлены в выбранной строке кода, что упрощает управление порядком выполнения путем замораживания и размораживания потоков. Run Flagged Threads to Cursor will pause threads on the selected line of code, making it easier to control the order of execution by freezing and thawing threads.

Чтобы снять или установить метку текущего выполняющегося потока, выберите флаг Переключить состояние пометки текущего потока слева от кнопки Показывать только помеченные потоки. To toggle the flagged or unflagged status of the currently executing thread, select the single flag Toggle Current Thread Flagged State toolbar button, to the left of the Show Only Flagged Threads button. Помечать текущий поток удобно для поиска текущего потока, когда отображаются только помеченные потоки. Flagging the current thread is useful for locating the current thread when only flagged threads are showing.

Чтобы снять метку с потока, наведите указатель мыши на маркер потока в исходном коде и выберите значок красного флажка, чтобы удалить его, или щелкните правой кнопкой мыши маркер потока и выберите Снять метку. To unflag a thread, hover over the thread marker in the source code and select the red flag icon to clear it, or right-click the thread marker and select Unflag.

Установка и снятие меток для потоков в окне «Потоки» Flag and unflag threads in the Threads window

В окне Потоки рядом с помеченными потоками стоит значок красного флажка, а у непомеченных потоков нет значков. In the Threads window, flagged threads have red flag icons next to them, while unflagged threads, if shown, have empty icons.

Выберите значок флага, чтобы изменить состояние потока на «помечено» или «не помечено» в зависимости от его текущего состояния. Select a flag icon to change the thread state to flagged or unflagged, depending on its current state.

Можно также щелкнуть правой кнопкой мыши строку и выбрать Пометить, Снять метку или Снять метку для всех потоков из контекстного меню. You can also right-click a line and select Flag, Unflag, or Unflag All Threads from the shortcut menu.

На панели инструментов в окне Потоки также есть кнопка Показывать только помеченные потоки (правая из двух значков с флагом). The Threads window toolbar also has a Show Flagged Threads Only button, which is the right-hand one of the two flag icons. Она работает так же, как кнопка на панели инструментов Место отладки, и обе кнопки управляют отображением в обоих расположениях. It works the same as the button on the Debug Location toolbar, and either button controls the display in both locations.

Другие функции окна «Потоки» Other Threads window features

В окне Потоки выберите заголовок любого столбца, чтобы отсортировать потоки по этому столбцу. In the Threads window, select the header of any column to sort the threads by that column. Щелкните еще раз, чтобы изменить порядок сортировки. Select again to reverse the sort order. Если отображаются все потоки, то при выборе столбца со значком флага выполняется сортировка потоков по наличию метки. If all threads are showing, selecting the flag icon column sorts the threads by flagged or unflagged status.

Вторым столбцом окна Потоки (без заголовка) является столбец Текущий поток. The second column of the Threads window (with no header) is the Current Thread column. Желтая стрелка в этом столбце отмечает текущую точку выполнения. A yellow arrow in this column marks the current execution point.

В столбце Расположение показано, где каждый поток отображается в исходном коде. The Location column shows where each thread appears in the source code. Щелкните стрелку «Развернуть» рядом с пунктом Расположение или наведите указатель мыши на пункт, чтобы отобразить частичный стек вызовов для этого потока. Select the expand arrow next to the Location entry, or hover over the entry, to show a partial call stack for that thread.

Для графического представления стеков вызовов для потоков используйте окно Параллельные стеки. For a graphical view of the call stacks for threads, use the Parallel Stacks window. Чтобы открыть это окно, во время отладки выберите Отладка> Окна > Параллельные стеки. To open the window, while debugging, select Debug> Windows > Parallel Stacks.

Помимо пунктов Пометить, Снять метку и Снять метку для всех потоков, в контекстном меню для окна Поток есть следующие элементы. In addition to Flag, Unflag, and Unflag All Threads, the right-click context menu for Thread window items has:

  • Кнопка Показать потоки в исходном коде. The Show Threads in Source button.
  • Шестнадцатеричное отображение, которое изменяет идентификатор потока в окне Потоки с десятичного на шестнадцатеричный формат. Hexadecimal display, which changes the Thread ID s in the Threads window from decimal to hexadecimal format.
  • Переключиться на поток — немедленное переключение на выполнение этого потока. Switch To Thread, which immediately switches execution to that thread.
  • Переименовать — изменение имени потока. Rename, which lets you change the thread name.
  • Команды Замораживание и размораживание. Freeze and Thaw commands.

Замораживание и размораживание выполнения потоков Freeze and thaw thread execution

Вы можете замораживать и размораживать (приостанавливать и возобновлять) потоки для управления порядком их выполнения. You can freeze and thaw, or suspend and resume, threads to control the order in which the threads perform work. Замораживание и размораживание потоков поможет устранить проблемы параллелизма, такие как взаимоблокировки и состояния гонки. Freezing and thawing threads can help you resolve concurrency issues, such as deadlocks and race conditions.

Для отслеживания одного потока без замораживания других потоков, что также является распространенным сценарием отладки, см. раздел Начало отладки многопоточных приложений. To follow a single thread without freezing other threads, which is also a common debugging scenario, see Get started debugging multithreaded applications.

Закрепление и снятие закрепления потоков: To freeze and unfreeze threads:

В окне Потоки щелкните правой кнопкой мыши любой поток и нажмите Заморозить. In the Threads window, right-click any thread and then select Freeze. Значок паузы в столбце Текущий поток указывает, что поток заморожен. A Pause icon in the Current Thread column indicates that the thread is frozen.

Выберите Столбцы на панели инструментов окна Потоки, а затем выберите Число приостановок, чтобы отобразить столбец Число приостановок. Select Columns in the Threads window toolbar, and then select Suspended Count to display the Suspended Count column. Значение числа приостановок для замороженного потока равно 1. The suspended count value for the frozen thread is 1.

Щелкните правой кнопкой мыши замороженный поток и выберите Разморозить. Right-click the frozen thread and select Thaw.

Значок паузы исчезает, а значение числа приостановок меняется на 0. The Pause icon disappears, and the Suspended Count value changes to 0.

Переключение на другой поток Switch to another thread

При попытке переключиться на другой поток может появиться окно Приложение находится в режиме приостановки выполнения. You may see a The application is in break mode window when you try to switch to another thread. В этом окне сообщается, что у потока нет кода, который может быть отображен текущим отладчиком. This window tells you that the thread does not have any code that the current debugger can display. Например, вы можете выполнять отладку управляемого кода, но поток является машинным кодом. For example, you may be debugging managed code, but the thread is native code. В окне предлагаются решения этой проблемы. The window offers suggestions for resolving the issue.

Переключение на другой поток To switch to another thread:

В окне Потоки запишите идентификатор текущего потока, который выделен желтой стрелкой в столбце Текущий поток. In the Threads window, make a note of the current thread ID, which is the thread with a yellow arrow in the Current Thread column. Переключитесь обратно на этот поток, чтобы продолжить работу приложения. You’ll want to switch back to this thread to continue your app.

Щелкните другой поток правой кнопкой мыши и выберите Переключиться на поток из контекстного меню. Right-click a different thread and select Switch To Thread from the context menu.

Обратите внимание, что положение желтой стрелки в окне Потоки изменилось. Observe that the yellow arrow location has changed in the Threads window. Исходный маркер текущего потока также остается в виде контура. The original current thread marker also remains, as an outline.

Взгляните на подсказку маркера потока в редакторе исходного кода и список в раскрывающемся меню Поток на панели инструментов Место отладки. Look at the tooltip on the thread marker in the code source editor, and the list in the Thread dropdown on the Debug Location toolbar. Обратите внимание, что указанный там текущий поток также изменился. Observe that the current thread has also changed there.

На панели инструментов Место отладки выберите другой поток из списка Поток. On the Debug Location toolbar, select a different thread from the Thread list. Обратите внимание, что текущий поток изменяется и в других двух расположениях. Note that the current thread changes in the other two locations also.

В редакторе исходного кода щелкните правой кнопкой мыши маркер потока, наведите курсор на пункт Переключиться на поток и выберите другой поток из списка. In the source code editor, right-click a thread marker, point to Switch To Thread, and select another thread from the list. Обратите внимание, что текущий поток изменяется во всех трех расположениях. Observe that the current thread changes in all three locations.

С помощью маркера потока в исходном коде можно переключаться только на потоки, остановленные в этом расположении. With the thread marker in source code, you can switch only to threads that are stopped at that location. С помощью окна Потоки и панели инструментов Место отладки можно переключиться на любой поток. By using the Threads window and Debug Location toolbar, you can switch to any thread.

Вы познакомились с основами отладки многопоточных приложений. You’ve now learned the basics of debugging multithreaded apps. Вы можете отслеживать, помечать и снимать метки, а также замораживать и размораживать потоки, используя окно Потоки, список Поток на панели инструментов Место отладки или маркеры потоков в редакторе исходного кода. You can observe, flag and unflag, and freeze and thaw threads by using the Threads window, the Thread list in the Debug Location toolbar, or thread markers in the source code editor.

Читайте также:  Патч для windows update
Оцените статью