I am trying to create and execute a thread using Windows CreateThread API. am seeing that running the program gives non-deterministic behavior. I am seeing from the output of the program that sometimes the thread method "my" gets executed and sometimes not. What might be the reason for this? The program is very simple as shown below. Also what should dwThreadID be initialized with. Should it be 0 or any integer value?
PS:Compiling in Visual Studio.
#include "stdafx.h"
#include <iostream>
#include <windows.h>
using namespace std;
// DWORD WINAPI
DWORD WINAPI my (LPVOID lpParam ) {
for (int i = 0; i < 5;i++){
cout << "I am ";
}
return 0;
}
int main()
{
DWORD dwThreadID = 0;
DWORD dwThrdParam = 0;
HANDLE h = NULL;
h = CreateThread(
NULL, // default security
0, // default stack size
my, // name of the thread function
0, // no thread parameters
0, // default startup flags
&dwThreadID);
if (h == NULL){
cout <<"It is null";
}
cout << " BBBB" << endl ;
CloseHandle(h);
cout << "BBBB ";
return 0;
}
I am seeing from the output of the program that sometimes the thread
method "my" gets executed and sometimes not. What might be the reason
for this?
Probably your main thread exits before your second thread is even executed. Place breakpoint after call to CreateThread.
Or even more cleaner wait, just wait for second thread using WaitForSingleObject.
This effectively make your main thread waiting until "my" thread is done.
If CreateThread fails for some reason, you can call GetLastError right after CreateThread, it will give you ultimate answer.
Also what should dwThreadID be initialized with.
Quick look into MSDN yields following:
A pointer to a variable that receives the thread identifier.
It is indeterminate whether or not your thread executes. The main thread creates it and then terminates the program. The following may happen:
The thread may execute before the main thread terminates.
The program may terminate before the thread executes.
The thread may partially execute and be terminated when the program terminates.
You would need to add synchronization in order to be sure that the thread reaches completion. Pass the thread handle to WaitForSingleObject.
Your program does not check for errors. CreateThread returns NULL when it fails. If that happens, and only if that happens, call GetLastError for information as to why the function failed. If you add a call to WaitForSingleObject then you should check its return value for errors as described by the documentation.
What should dwThreadID be initialized with?
It does not need to be initialized because CreateThread guarantees it will be assigned if CreateThread succeeds.
Firstly do not use CreateThread it is intended for library providers. Use beginthreadex or std::thread
The likely behavior, is that the thread always runs, but it's output is being overwritten. This is because there is no synchronisation.
Check the return code and GetLastError
The value of dwThreadid does not matter
Related
Why does Sleep() stop all created threads? I want to create a thread but keep the Main function in sleep until the thread finishes.
bool _finished = false;
void testcount(void *p){
int i = 0;
while(i<=30){
i++;
std::cout<<i<<"\n";
Sleep(1000);
}
_finished = true;
}
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved){
HANDLE test = NULL;
test = CreateThread(NULL, NULL, (LPTHREAD_START_ROUTINE)testcount, NULL, NULL, NULL);
if(test)
std::cout<<"test thread created";
CloseHandle(test);
while(!_finished)
Sleep(1000);
return true;
}
I am trying it now like this, but the program just never finishes, because while with Sleep stops the thread. I don't want to return anything on Main while thread not finished. Any solution?
Calls to DllMain are serialised by Win32.
All new threads start by calling DllMain (with thread attach flag), and the call the method passed to CreateThread.
Therefore your thread is waiting to call DllMain, which cannot happen until your first thread leaves DllMain.
As commenter John Sheridan notes Raymond Chen's blog post from 2007 is a really good explanation.
PS. for correct C/C++ library initialisation you should be using _beginthread or _beginthreadex rather than CreateThread directly.
The new thread is blocked because your main thread does not leave DllMain, as described in Richard's answer.
Your code also contains a data race and has undefined behavior even after this deadlock is fixed. The new thread writes to _finished, the main thread reads from _finished, concurrently. You could try to use std::atomic<bool> instead of bool to fix this, assuming availability of C++11, or you could use Win32 primitives for thread synchronization.
Changes for standard solution using std::atomic<bool>:
#include <atomic>
std::atomic<bool> finished_{false};
// Rest remains the same
In my Windows service application I may resort to calling TerminateThread API on some of the threads in my process. (Note that I do so only as a last resort measure when a thread fails to quit in a "normal fashion" using signaling mechanism and thread synchronization techniques.) What I've noticed in the event log submitted by a customer is that very rarely TerminateThread may throw the STATUS_INVALID_THREAD exception, which happens only when that API is called on a thread belonging to a threadpool.
Since I know for sure that none of my threads are started from a threadpool, the thread that my call to TerminateThread attempts to close must be coming from another process. This could happen only due to a race condition where my thread handle is closed first and then is passed again to the TerminateThread API while the OS reuses it for some other thread in another process.
So my question is, since my service is running with sufficiently high privileges (as localService) can TerminateThread API in this situation inadvertently terminate some thread belonging to another process? And if yes, how can I prevent this (apart from finding the race-condition, that I'm doing now)?
Let's let the docs speak for themselves:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms686717(v=vs.85).aspx
Do not use TerminateThread():
TerminateThread is a dangerous function that should only be used in the most extreme cases. You should call TerminateThread only if you know exactly what the target thread is doing, and you control all of the code that the target thread could possibly be running at the time of the termination. For example, TerminateThread can result in the following problems:
[...]
You can terminate any thread, as long as you have a handle with sufficient privileges:
A thread cannot protect itself against TerminateThread, other than by controlling access to its handles. The thread handle returned by the CreateThread and CreateProcess functions has THREAD_TERMINATE access, so any caller holding one of these handles can terminate your thread.
Note that I do so only as a last resort measure when a thread fails to quit in a "normal fashion" using signaling mechanism and thread synchronization techniques.
That is a case where you cannot call TerminateThread. You can only call TerminateThread if you have precise control over the thread you are terminating and its full cooperation. If the thread fails to quit in the normal fashion, then you have lost control over the thread, the very opposite of the required conditions under which you can call TerminateThread.
If a process has lost control over one of its threads, the process cannot be saved. This is a fundamental property of threads -- they do not provide isolation of anything but flow control.
If you must do this you can do it like this.
All you need to start is the thread handle.
You call the first function with thread handle as input using the "undocumented" NtQueryInformationThread() function with the ThreadQuerySetWin32StartAddress argument, you get the StartAddress of the thread. More reading # NTInternals.
It calls NTQueryInformationThread by function address after getting the address via GetProcAddress. Then it calls it with the ThreadQuerySetWin32StartAddress argument, getting the StartAddress of the thread.
Then you call the second function which loops through all the threads via CreateToolHelp32Snapshot and compares against the supplied StartAddress. It calls TerminateThread once it finds it.
enum THREADINFOCLASS
{
ThreadQuerySetWin32StartAddress = 9,
};
typedef NTSTATUS(__stdcall * f_NtQueryInformationThread)(HANDLE, THREADINFOCLASS, void*, ULONG_PTR, ULONG_PTR*);
ULONG_PTR GetThreadStartAddress(HANDLE hThread)
{
auto NtQueryInformationThread = reinterpret_cast<f_NtQueryInformationThread>(GetProcAddress(GetModuleHandleA("ntdll.dll"), "NtQueryInformationThread"));
if (!NtQueryInformationThread)
return 0;
ULONG_PTR ulStartAddress = 0;
NTSTATUS Ret = NtQueryInformationThread(hThread, ThreadQuerySetWin32StartAddress, &ulStartAddress, sizeof(ULONG_PTR), nullptr);
if (NT_FAIL(Ret))
return 0;
return ulStartAddress;
}
bool TerminateThreadByStartaddress(ULONG_PTR StartAddress)
{
HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
if (hSnap == INVALID_HANDLE_VALUE)
return false;
THREADENTRY32 TE32 = { 0 };
TE32.dwSize = sizeof(THREADENTRY32);
BOOL Ret = Thread32First(hSnap, &TE32);
while (Ret)
{
HANDLE hTempThread = OpenThread(THREAD_ALL_ACCESS, FALSE, TE32.th32ThreadID);
if (!hTempThread)
{
Ret = Thread32Next(hSnap, &TE32);
continue;
}
if (StartAddress == GetThreadStartAddress(hTempThread))
{
TerminateThread(hTempThread, 0);
CloseHandle(hTempThread);
CloseHandle(hSnap);
return true;
}
CloseHandle(hTempThread);
Ret = Thread32Next(hSnap, &TE32);
}
CloseHandle(hSnap);
return false;
}
Credits to my friend Broihon, I didn't write this code but have used it before.
Use undocumented NTSYSAPI NTSTATUS NTAPI NtTerminateThread(IN HANDLE ThreadHandle, IN NTSTATUS ExitStatus); from http://undocumented.ntinternals.net where ThreadHandle is result from OpenThread MS function and ExitStatus set to whatever you want.
I am having a strange behavior: WaitForSingleObject seems to crash when I return 0 from my thread, but if I call "ExitThread(0)" then it does not.
void waitForThread(DWORD &threadId)
{
HANDLE hThread = OpenThread(SYNCHRONIZE,
FALSE,
threadId);
if (hThread == NULL) return;
WaitForSingleObject(hThread, INFINITE); // Crashes here (not even returning)
CloseHandle(hThread);
}
According to the documentation:
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.
This does not make sense to me. I would think that "return 0" in my function with the signature:
DWORD WINAPI foo(LPVOID arg);
would be fine. For completeness, the thread is created using CreateThread, as such:
DWORD threadId;
HANDLE pth = CreateThread(NULL, // Default security attributes
0, // Default stack size
foo, // Thread name
arg, // Argument to thread
0, // Default creation flag
&threadId); // Returns thread ID
Does anyone know why the return statement would crash "WaitForSingleObject" please? I have put print statement before and after WaitForSingleObject, and one when the thread exists, and the behavior I see is: "Before WaitForSingleObject", "Thread finishes", Crash. Does anyone understand this behavior please?
So I have been learning about threads in the Windows API, and I wrote some test code, but I am have some issues. First off I have two functions:
DWORD WINAPI MyThreadFunction( LPVOID lpParam )
{
int i = (int)lpParam;
cout << i << ".) I work! " << endl;
return 0;
}
And
// MyThreadFunction2 - loops continuously forever, outputing "working..." every 1ms
DWORD WINAPI MyThreadFunction2( LPVOID lpParam )
{
int i = (int)lpParam;
while(1) {
cout << i << ".) Working... " << endl;
Sleep(1);
}
return 0;
}
And I am creating threads using CreateThread, but I will change that later to _beginThread which is what people have told me to do in a different but related post. So this is how I have been creating threads:
threads.push_back(CreateThread(
NULL, // default security attributes
0, // use default stack size
lpStartAddress, // thread function name
lpParameter, // arugument to thread function
0, // use default creation flag
NULL)); // ignore thread identifier.
I am putting the thread HANDLEs I create into a vector, but that is irrelevant. Basically I have the above code working, and it creates the threads fine. The problem I am having is calling TerminateThread(HANDLE, 0) when the thread was created using MyThreadFunction2, where it loops forever. When I call TerminateThread, my program just freezes and sits there. It appears the thread has stopped, because I don't get the "Working..." message, but it doesn't continue any other code. However, when I call this same function when it is with MyThreadFunction, it works fine.
I don't know if this is extremely confusing how I am explaining what is going on, I hope it isn't. I know this isn't a place to "just dump code, and have people fix it" - I read that on someone else's post, but just incase you didn't understand a thing I wrote above, or it is helpful, here is my code:
ThreadManager.cpp
http://pastebin.com/0B1N3TAH
ThreadManager.h
http://pastebin.com/yfwMJTaz
Sorry the code is poorly written, and some things aren't complete. I am still working on re-learning C++ and learning how to use the Windows API. But does anyone have any ideas of what I might possibly be doing wrong?
Using TerminateThread to kill a thread is generally a really bad idea. Even MSDN page for this function tells you that. A better way to tell the threads to stop working is to pass them an event. With an event the thread that runs an infinite loop would do while (WaitForSingleObject(event, 1) == WAIT_TIMEOUT) instead of while (1).
Why exactly TerminateThread does what it dies, I don't know, but you can get an idea of what might be wrong when you read this http://msdn.microsoft.com/en-us/library/windows/desktop/ms686717(v=vs.85).aspx
Here is my problem:
I'm creating threads
HANDLE Threads[THREAD_NUM]
Launch the thread
void LaunchThread (int i) {
*some checks if the handle is not null etc*;
DWORD threadId;
threads[i] = CreateThread (
NULL,
0,
(LPTHREAD_START_ROUTINE)*StaticMethodInvokingTheThreadFunc,
*StructPassingToThatMethod ( basically have a pointer and thread number)*,
0,
&threadId);
*DebugMessage "thread created"*;
*DebugMessage "with id = (threadId)"*;
}
Static method invokes function
void DoSmth () {
*DebugMessage "thread func started"*;
...;
*then code with another messages all the way*;
}
Waiting function is simple
void WaitThread (i){
*DebugMessage "wait for thread to finish"*;
WaitForSingleObject (Threads[i], INFINITE);
}
And in main function the sequence:
LaunchThread (i);
WaitThread (i);
Program never returns the WaitThread () function, and(!) the list of messages looks like
"thread created"
"thread func started" (and nothing done after that message in DoSmth () func)
"with id = .."
"wait for thread to finish"
This happens even with 1 thread...
For a couple of threads i simply have
for ( int t = 0; t < THREAD_NUM; t++)
LaunchThread (t);
and the same loop for waiting threads
Why is this happening?
I tried to ResumeThread (), to close handle to thread and relaunch it, but nothing helped.
It could be that function StaticMethodInvokingTheThreadFunc does not really have a signature of LPTHREAD_START_ROUTINE, but this is masked by the fact that the function pointer is forcefully cast to it. Remove the cast. If compiler starts to complain then adapt the signature of your function.
It could be that calling CreateThread is wrong in your case. It is wrong in 99% cases, and you should really call CRT library function _beginthreadex. This function internally calls CreateThread, but it also does some initialization stuff. Replace CreateThread with _beginthreadex.
It could be that the execution is hang in StaticMethodInvokingTheThreadFunc, after the text "thread func started" is printed. Revise the code in the function, or place a breakpoint on last function's line and debug the project to see if breakpoint will be hit.