Windows thread stack address

CreateThread function (processthreadsapi.h)

Creates a thread to execute within the virtual address space of the calling process.

To create a thread that runs in the virtual address space of another process, use the CreateRemoteThread function.

Syntax

Parameters

A pointer to a SECURITY_ATTRIBUTES structure that determines whether the returned handle can be inherited by child processes. If lpThreadAttributes is NULL, the handle cannot be inherited.

The lpSecurityDescriptor member of the structure specifies a security descriptor for the new thread. If lpThreadAttributes is NULL, the thread gets a default security descriptor. The ACLs in the default security descriptor for a thread come from the primary token of the creator.

The initial size of the stack, in bytes. The system rounds this value to the nearest page. If this parameter is zero, the new thread uses the default size for the executable. For more information, see Thread Stack Size.

A pointer to the application-defined function to be executed by the thread. This pointer represents the starting address of the thread. For more information on the thread function, see ThreadProc.

A pointer to a variable to be passed to the thread.

The flags that control the creation of the thread.

Value Meaning
0 The thread runs immediately after creation.
CREATE_SUSPENDED 0x00000004 The thread is created in a suspended state, and does not run until the ResumeThread function is called.
STACK_SIZE_PARAM_IS_A_RESERVATION 0x00010000 The dwStackSize parameter specifies the initial reserve size of the stack. If this flag is not specified, dwStackSize specifies the commit size.

A pointer to a variable that receives the thread identifier. If this parameter is NULL, the thread identifier is not returned.

Return value

If the function succeeds, the return value is a handle to the new thread.

If the function fails, the return value is NULL. To get extended error information, call GetLastError.

Note that CreateThread may succeed even if lpStartAddress points to data, code, or is not accessible. If the start address is invalid when the thread runs, an exception occurs, and the thread terminates. Thread termination due to a invalid start address is handled as an error exit for the thread’s process. This behavior is similar to the asynchronous nature of CreateProcess, where the process is created even if it refers to invalid or missing dynamic-link libraries (DLLs).

Remarks

The number of threads a process can create is limited by the available virtual memory. By default, every thread has one megabyte of stack space. Therefore, you can create at most 2,048 threads. If you reduce the default stack size, you can create more threads. However, your application will have better performance if you create one thread per processor and build queues of requests for which the application maintains the context information. A thread would process all requests in a queue before processing requests in the next queue.

The new thread handle is created with the THREAD_ALL_ACCESS access right. If a security descriptor is not provided when the thread is created, a default security descriptor is constructed for the new thread using the primary token of the process that is creating the thread. When a caller attempts to access the thread with the OpenThread function, the effective token of the caller is evaluated against this security descriptor to grant or deny access.

The newly created thread has full access rights to itself when calling the GetCurrentThread function.

Windows ServerВ 2003:В В The thread’s access rights to itself are computed by evaluating the primary token of the process in which the thread was created against the default security descriptor constructed for the thread. If the thread is created in a remote process, the primary token of the remote process is used. As a result, the newly created thread may have reduced access rights to itself when calling GetCurrentThread. Some access rights including THREAD_SET_THREAD_TOKEN and THREAD_GET_CONTEXT may not be present, leading to unexpected failures. For this reason, creating a thread while impersonating another user is not recommended.

If the thread is created in a runnable state (that is, if the CREATE_SUSPENDED flag is not used), the thread can start running before CreateThread returns and, in particular, before the caller receives the handle and identifier of the created thread.

The thread execution begins at the function specified by the lpStartAddress parameter. If this function returns, the DWORD return value is used to terminate the thread in an implicit call to the ExitThread function. Use the GetExitCodeThread function to get the thread’s return value.

The thread is created with a thread priority of THREAD_PRIORITY_NORMAL. Use the GetThreadPriority and SetThreadPriority functions to get and set the priority value of a thread.

When a thread terminates, the thread object attains a signaled state, satisfying any threads that were waiting on the object.

The thread object remains in the system until the thread has terminated and all handles to it have been closed through a call to CloseHandle.

The ExitProcess, ExitThread, CreateThread, CreateRemoteThread functions, and a process that is starting (as the result of a call by CreateProcess) are serialized between each other within a process. Only one of these events can happen in an address space at a time. This means that the following restrictions hold:

  • During process startup and DLL initialization routines, new threads can be created, but they do not begin execution until DLL initialization is done for the process.
  • Only one thread in a process can be in a DLL initialization or detach routine at a time.
  • ExitProcess does not complete until there are no threads in their DLL initialization or detach routines.

A thread in an executable that calls the C run-time library (CRT) should use the _beginthreadex and _endthreadex functions for thread management rather than CreateThread and ExitThread; this requires the use of the multithreaded version of the CRT. If a thread created using CreateThread calls the CRT, the CRT may terminate the process in low-memory conditions.

Windows Phone 8.1: This function is supported for Windows Phone Store apps on Windows Phone 8.1 and later.

WindowsВ 8.1 and Windows ServerВ 2012В R2: This function is supported for Windows Store apps on WindowsВ 8.1, Windows ServerВ 2012В R2, and later.

Пошаговое руководство. Отладка многопоточного приложения с помощью окна «Потоки» (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.

Читайте также:  Хорошая pdf читалка для windows

Выполнение этого учебника занимает всего несколько минут, в ходе которых вы ознакомитесь с основами отладки многопоточных приложений. 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 .

Читайте также:  Как найти персонализацию для windows 10

Чтобы различать безымянные потоки, их можно переименовать в окне Потоки. 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.

Читайте также:  Что читает windows player для windows

Вторым столбцом окна Потоки (без заголовка) является столбец Текущий поток. 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.

Оцените статью