ExitThread function (processthreadsapi.h)
Ends the calling thread.
Syntax
Parameters
The exit code for the thread.
Return value
Remarks
ExitThread is the preferred method of exiting a thread in C code. However, in C++ code, the thread is exited before any destructors can be called or any other automatic cleanup can be performed. Therefore, in C++ code, you should return from your thread function.
When this function is called (either explicitly or by returning from a thread procedure), the current thread’s stack is deallocated, all pending I/O initiated by the thread is canceled, and the thread terminates. The entry-point function of all attached dynamic-link libraries (DLLs) is invoked with a value indicating that the thread is detaching from the DLL.
If the thread is the last thread in the process when this function is called, the thread’s process is also terminated.
The state of the thread object becomes signaled, releasing any other threads that had been waiting for the thread to terminate. The thread’s termination status changes from STILL_ACTIVE to the value of the dwExitCode parameter.
Terminating a thread does not necessarily remove the thread object from the operating system. A thread object is deleted when the last handle to the thread is closed.
The ExitProcess, ExitThread, CreateThread, CreateRemoteThread functions, and a process that is starting (as the result of a CreateProcess call) are serialized between each other within a process. Only one of these events can happen in an address space at a time. This means 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 return until no threads are in their DLL initialization or detach routines.
A thread in an executable that is linked to the static C run-time library (CRT) should use _beginthread and _endthread for thread management rather than CreateThread and ExitThread. Failure to do so results in small memory leaks when the thread calls ExitThread. Another work around is to link the executable to the CRT in a DLL instead of the static CRT. Note that this memory leak only occurs from a DLL if the DLL is linked to the static CRT and a thread calls the DisableThreadLibraryCalls function. Otherwise, it is safe to call CreateThread and ExitThread from a thread in a DLL that links to the static CRT.
Use the GetExitCodeThread function to retrieve a thread’s exit code.
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.
Как завершать потоки?
Создал поток, а завершить немогу.
Поток можно завершить четырьмя способами:
1)функция потока возвращает управление;
2)поток самоуничтожается вызовом функции ExitThread;
3)другой поток процесса вызывает функцию TerminateThread;
4)завершается процесс, содержащий данный поток.
Как завершить его первым способом?
Как правильно завершать поток?
есть код: #include «stdafx.h» DWORD WINAPI PoolThread(LPVOID); int _tmain(int argc, _TCHAR*.
Помогите понять как завершать потоки
Не могу понять как остановить программу корректно чтобы она не оставалась в процессах Вот такой.
Как правильно завершать процес даемона ?
Всем привет ! Вот такая проблема — пишу сокет сервер — ну и понятное дело нужно тестить.
а чем поток занимается, что завершить не получается?
первый случай: поток сделал все, что надо, и сделал return;.
есть еще вариант: потоку можно послать сообщение. только он должен его принять и обработать.
Первый случай не подходит. Какое сообщение нужно послать, и как его обрабатывать?
Добавлено через 10 минут
И ещё вопрос: в моём потоке задаётся бесконечный цикл и он очень сильно грузит процессор. Есть ли способ приостанавливать этот цикл, кроме Sleep();
Тематические курсы и обучение профессиям онлайн Профессия Разработчик на C++ (Skillbox) Архитектор ПО (Skillbox) Профессия Тестировщик (Skillbox) |
Заказываю контрольные, курсовые, дипломные и любые другие студенческие работы здесь или здесь.
Как правильно завершать действия в MVC?
Здравствуйте. Подскажите, у меня есть mvc система и есть страница с добавлением картинок.
Как после работы с COM компонентами завершать их
Всем привет! Как после работы с COM компонентами завершать их. (На пример работа с MS- WORD)
Как правильно завершать дочерний поток?
Всем доброго времени суток! Есть некий объект в котором запускается дочерний поток и в нем.
Как запретить пользователю завершать процесс приложения
Поковырял, многое но не нашел! Как сделать процесс системным? чтоб пользователь его не мог.
Set thread exit code manually in C#?
Is there a way to set the thread exit code manually in C# (for debugging purposes)?
The selected answer of a related question «What is a thread exit code?» states:
0 tends to mean that it exited safely whilst anything else tends to mean it didn’t exit as expected. But then this exit code can be set in code by yourself to completely overlook this.
Is there really a way to set a thread’s exit code myself?
1 Answer 1
.NET threads do not have exit codes. Those are used by the native threads on Windows, but native threads are only used by managed threads, and have no 1:1 correspondence to a given managed thread. The same managed thread can run on multiple native threads and vice versa (though obviously not at the same time). To quote MSDN:
An operating-system ThreadId has no fixed relationship to a managed thread, because an unmanaged host can control the relationship between managed and unmanaged threads. Specifically, a sophisticated host can use the Fiber API to schedule many managed threads against the same operating system thread, or to move a managed thread among different operating system threads.
This of course applies to all resources tied to the native thread — but the runtime does manage the managed resources of a thread, of course; and for unmanaged code calling into managed code, the thread will be kept the same — otherwise interop would be quite impossible.
How do I get the application exit code from a Windows command line?
I am running a program and want to see what its return code is (since it returns different codes based on different errors).
I know in Bash I can do this by running
What do I do when using cmd.exe on Windows?
7 Answers 7
A pseudo environment variable named errorlevel stores the exit code:
Also, the if command has a special syntax:
See if /? for details.
Example
Warning: If you set an environment variable name errorlevel , %errorlevel% will return that value and not the exit code. Use ( set errorlevel= ) to clear the environment variable, allowing access to the true value of errorlevel via the %errorlevel% environment variable.
Testing ErrorLevel works for console applications, but as hinted at by dmihailescu, this won’t work if you’re trying to run a windowed application (e.g. Win32-based) from a command prompt. A windowed application will run in the background, and control will return immediately to the command prompt (most likely with an ErrorLevel of zero to indicate that the process was created successfully). When a windowed application eventually exits, its exit status is lost.
Instead of using the console-based C++ launcher mentioned elsewhere, though, a simpler alternative is to start a windowed application using the command prompt’s START /WAIT command. This will start the windowed application, wait for it to exit, and then return control to the command prompt with the exit status of the process set in ErrorLevel .
What is a thread exit code?
What exactly is a thread exit code in the Output window while debugging? What information it gives me? Is it somehow useful or just an internal stuff which should not bother me?
Is there maybe some sort of list of possible exit codes along with its significance?
3 Answers 3
There actually doesn’t seem to be a lot of explanation on this subject apparently but the exit codes are supposed to be used to give an indication on how the thread exited, 0 tends to mean that it exited safely whilst anything else tends to mean it didn’t exit as expected. But then this exit code can be set in code by yourself to completely overlook this.
The closest link I could find to be useful for more information is this
Quote from above link:
What ever the method of exiting, the integer that you return from your process or thread must be values from 0-255(8bits). A zero value indicates success, while a non zero value indicates failure. Although, you can attempt to return any integer value as an exit code, only the lowest byte of the integer is returned from your process or thread as part of an exit code. The higher order bytes are used by the operating system to convey special information about the process. The exit code is very useful in batch/shell programs which conditionally execute other programs depending on the success or failure of one.
From the Documentation for GetEXitCodeThread
Important The GetExitCodeThread function returns a valid error code defined by the application only after the thread terminates. Therefore, an application should not use STILL_ACTIVE (259) as an error code. If a thread returns STILL_ACTIVE (259) as an error code, applications that test for this value could interpret it to mean that the thread is still running and continue to test for the completion of the thread after the thread has terminated, which could put the application into an infinite loop.
My understanding of all this is that the exit code doesn’t matter all that much if you are using threads within your own application for your own application. The exception to this is possibly if you are running a couple of threads at the same time that have a dependency on each other. If there is a requirement for an outside source to read this error code, then you can set it to let other applications know the status of your thread.