c thread in windows HWND error - c

Below is my code.it getting a Handle mistake.
`
int main(){
HWND hMainWin;
DWORD threadID;
//Create thread down
HANDLE threadHandle = CreateThread(NULL,
0,
threadFunction,
(LPVOID)hMainWin,
0,
&threadID);
}
DWORD WINAPI threadFunction(LPVOID param){ //my thread function
HANDLE hwnd = (HANDLE)param;
for(int i=0;i<5;i++)
{
printf("hello");
}
return 0;
}
Error:

You have a variable HWND hMainWin; that is not initialized and you are using that (uninitialized) variable as argument #4 in a call to CreateThread(). Since the variable is uninitialized its value is undefined which is the reason for the error message you are getting.
From the looks of it your code seems to be a console application. As such you don't have a window or a handle to it (the HWND) thus you are having trouble initializing the hMainWin.
It looks like that parameter is just a dummy variable (not really used in your thread function) so you might as well (just for a "quick fix") initialize it with a NULL (or a 0)

Related

How to write data into global variables from callback function?

According to windows API docs we can use global variable to pass data from creating thread to the new thread and I am assuming the opposite is also possible
Data can also be passed from the creating thread to the new thread using global variables.
Here is a data structure and a callback function, ptr is a pointer to heap allocated memory in main
typedef struct Output
{
char *ptr;
DWORD len;
}Output, *POutput;
Output out; // global variable
DWORD grab_output(LPVOID args)
{
DWORD dread;
BOOL success = FALSE;
while (1)
{
success = ReadFile(g_hChildStd_OUT_Rd,out.ptr, 1024, &dread, NULL);
if (!success || dread == 0 ) break;
out.ptr = realloc(out.ptr, out.len+1024);
out.len += dread;
}
}
int run()
{
BOOL res;
STARTUPINFO si;
PROCESS_INFORMATION pi;
SECURITY_ATTRIBUTES sa;
DWORD dwThreadIdArray[1];
DWORD n_size;
memset(&si, 0 ,sizeof(si));
memset(&pi, 0, sizeof(pi));
memset(&sa, 0, sizeof(sa));
sa.nLength = sizeof(SECURITY_ATTRIBUTES);
sa.bInheritHandle = TRUE;
sa.lpSecurityDescriptor = NULL;
if (!CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &sa, 0))
return GetLastError();
if (!SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0))
return GetLastError();
si.cb = sizeof(STARTUPINFOA);
si.hStdError = g_hChildStd_OUT_Wr;
si.hStdOutput = g_hChildStd_OUT_Wr;
si.dwFlags |= STARTF_USESTDHANDLES;
if(!CreateProcess(NULL,
"C:\\Windows\\System32\\cmd.exe /c dir",
NULL,
NULL,
TRUE,
CREATE_NEW_CONSOLE,
NULL,
NULL,
&si,
&pi
))
{
}
else
{
handle = CreateThread(0, 0, grab_output, NULL, 0, NULL);
}
return 0;
}
int main()
{
out.ptr = malloc(1024);
out.len = 0;
run();
printf("%s\n", out.ptr);
}
when running the code out.ptr returns garbage values
gcc example.c && ./a.exe
└e╔┐═☺
for the sake of this question assume that I will be running a single thread at any given time
The reason this prints garbage values is you assumed for no clear reason that the thread finishes before you accessed the global variable.
There's too many unchecked fault points. Right now, check every function that can error for an error return and produce output in that case, and also set a flag in another global variable. Really, you shouldn't have to, but better to much than not enough. Then close the process and thread handles you aren't using.
Now we should be able to discuss synchronization.
It looks like you want to grab all of the output at once. Thus WaitForSingleObject() on your own thread handle. To produce output incrementally, you need to track input highwater and output highwater and output only the characters in between with putc().
Don't forget to null-terminate your string either, or printf() won't be happy.
You need some means to communicate between the thread and main() that the value has been updated. It is very likely that main() will execute the printf before the thread is done with ReadFile. Also you have a race condition where ReadFile might be writing to the buffer while printf is reading it.
Use a mutex, semaphore, event or similar to communcate between threads, then use WaitForSingleObject etc where appropriate. It's also not advisable to have a busy-loop inside the thread or to exit the creator thread main() while there are threads still running.
EDIT:
Note that you must also return 0 from the thread or your program will go haywire, if you somehow managed to get it compiling in the first place despite the missing return.

WINAPI how to wait until all threads finish?

I want to simulate Java's behavior of waiting until all threads in the process finish before the main exits in C/Windows API.
The behavior I want to simulate is one of the sample code below(it spams [second thread] active threads: 2., and does not terminate even when main returns):
public final class Test1
{
// | prints current thread count and queues the next iteration.
static void step() {
System.out.println (
"[second thread] active threads: " +
Thread.activeCount() +
"."
);
new Thread(() -> step()).start();
}
public static void main(String[] args) throws Exception
{
// | queue the first iteration.
new Thread(() -> step()).start();
}
}
My initial idea was to completely take over the main of my program, and instead do all the work in another function, eg main2 and if it finishes early, I will wait until the rest of the threads finish.
My problem is that my main has no idea what other threads exist, and even if it did know what other threads existed, after they all finish, it is still possible that they have spawned more threads, that we are again not aware of.
My approach to tackle this looks something as follows:
main.c would contain the actual main, and the actual main logic would be moved out to main2(or something with a better name). main would potentially resort to using CreateToolhelp32Snapshot to discover threads that do not match its own GetThreadId and wait for them(potentially aggregating existing threads to avoid only fetching one existing thread at a time, to take advantage of WaitForMultipleObjects).
/**
* #file main.c
*/
#include <Windows.h>
// | This function will can start threads without worrying about them
// | ending as soon as it finishes.
extern int main2(int argc, char **argv);
// | NOT IMPLEMENTED: I have no idea if such a service exists, but it can probably be
// | implemented using CreateToolhelp32Snapshot.
// | If it did exist, it would return a single thread from the process
// | not matching the current thread id.
extern HANDLE WINAPI SorceryToDiscoverASingleOtherThreadThatExists();
int main(int argc, char **argv)
{
int returnValue;
// | main2 will do the actual main's work.
returnValue = main2(argc, argv);
// | Do not finish before other threads finish.
for (;;) {
HANDLE hThread;
// | Find a single thread handle whose thread id is
// | not the same as the current thread's.
hThread = SorceryToDiscoverASingleOtherThreadThatExists();
// | If there are no more threads,
// | we can finally break out of this infinite loop.
if (hThread == 0) {
break;
}
WaitForSingleObject(hThread, INFINITE);
}
return 0;
}
And main2.c which would behave as our java program would:
/**
* #file main2.c
*/
#include <Windows.h>
#include <stdio.h>
DWORD CALLBACK ThreadProc0001(LPVOID unused) {
puts("Hello, World!");
CreateThread(0, 0, ThreadProc0001, 0, 0, 0);
return 0;
}
int main2(int argc, char **argv)
{
CreateThread(0, 0, ThreadProc0001, 0, 0, 0);
return 0;
}
With proof of concept to make sure the above code works(deep_thread_nesting.c):
/**
* #file deep_thread_nesting.c
*/
#include <Windows.h>
#include <stdio.h>
DWORD CALLBACK ThreadProc0001(LPVOID unused) {
puts("Hello, World!");
CreateThread(0, 0, ThreadProc0001, 0, 0, 0);
return 0;
}
int main(int argc, char **argv)
{
CreateThread(0, 0, ThreadProc0001, 0, 0, 0);
// | Do not exit until user presses ctrl c.
for (;;) {
// | Reduce strain on the CPU from the infinite loop.
Sleep(1000);
}
return 0;
}
My problem is that I feel forced to use one of three incredibly ugly solutions:
The first involving the mystical CreateToolhelp32Snapshot function as this tutorial describes, in order to fetch one(or potentially be optimized further to return more than one thread that does not match our active thread id) thread handle(s) that we can use to wait on.
The second involving keeping a global registry of all the handles and having each thread lock the world, add the handle to the registry, remove its own handle, and unlock the world, possibly writing my own CreateThread wrapper that takes care of this for me.
The third being a rough idea, as I have no idea if this even works the way I think it does, hooking the CreateThread function to make all threads implement the second solution.
Question
Is there a way to make C or Windows API wait for all my threads to finish
before terminating the program without effectively writing my own runtime?
Not really an answer, but, as mentioned by IInspectable, ExitProcess is called by the CRT. So getting rid of the CRT the behaviour that you are looking for is restored.
Compile with /NODEFAULTLIB, include libraries using the command line and not #pragma comment(lib, ...).
#include <Windows.h>
DWORD WINAPI other_thread(LPVOID lpThreadParameter)
{
HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
if ((hOut == INVALID_HANDLE_VALUE) ||
(!hOut))
{
if (IsDebuggerPresent()) __debugbreak();
return -1;
}
constexpr char string[] = "I am writing!\r\n";
for (;;)
{
WriteFile(hOut, string, sizeof(string), 0, 0);
}
return 0;
}
int mainCRTStartup()
{
HANDLE hThread = CreateThread(0, 0, other_thread, 0, 0, 0);
return 1;
}
The other_thread continues writing, even after the mainCRTStartup exits.
An answer that is closer to what the OP intended:
#include <windows.h>
#pragma comment(lib, "synchronization.lib")
// the program will not (usually) exit, until this counter is at 0
long long deployed_threads_counter;
// we need a place to store the user's function pointer,
// as the lpStartAddress parameter of CreateThread is already used
struct ThreadParameters
{
LPTHREAD_START_ROUTINE lpStartAddress;
LPVOID lpParameter;
};
// a wrapper around the user provided LPTHREAD_START_ROUTINE
DWORD WINAPI my_thread_start(LPVOID lpThreadParameter)
{
// dereferenced! my_create_thread can now exit
ThreadParameters thread_parameters = *(ThreadParameters*)lpThreadParameter;
WakeByAddressSingle(lpThreadParameter);
// actually do the work
BOOL result = thread_parameters.lpStartAddress(thread_parameters.lpParameter);
// signal that the thread has finished executing
InterlockedDecrement64(&deployed_threads_counter);
WakeByAddressSingle(&deployed_threads_counter);
return result;
}
// CreateThread substitude incurs the desired behaviour
HANDLE my_create_thread(
LPSECURITY_ATTRIBUTES lpThreadAttributes,
SIZE_T dwStackSize,
LPTHREAD_START_ROUTINE lpStartAddress,
LPVOID lpParameter,
DWORD dwCreationFlags,
LPDWORD lpThreadId)
{
InterlockedIncrement64(&deployed_threads_counter);
ThreadParameters thread_parameters =
{
lpStartAddress,
lpParameter,
};
// call my_thread_start instead, so that the thread exit is signaled
HANDLE hThread = CreateThread(
lpThreadAttributes,
dwStackSize,
my_thread_start,
&thread_parameters,
dwCreationFlags,
lpThreadId);
// do not destroy thread_parameters, until my_thread_start has finished using them
WaitOnAddress(&thread_parameters, &lpStartAddress, sizeof(LPTHREAD_START_ROUTINE), INFINITE);
return hThread;
}
// optionally set this behaviour to be the default
#define CreateThread my_create_thread
int use_this_main();
int main()
{
// execute user code
int result = use_this_main();
// wait for all threads to finish
while (auto temp = deployed_threads_counter)
{
WaitOnAddress(&deployed_threads_counter, &temp, sizeof(temp), INFINITE);
}
// fallthrough return
return result;
}
int use_this_main()
{
// your code here...
return 0;
}
Currently there is actually a race condition, if InterlockedIncrement64 is called after the main's WaitOnAddress. This can be prevented, with something like a double gate system, but the answer is already complicated enough.

How to close Thread by using the library windows.h (in c)

I wish to create a Thread that will always run until I force him to be close.
I programming in c language, and uses the library windows.h
adding my code of creating thread:
HANDLE thread;
DWORD threadID;
thread = CreateThread(NULL, 0, infinitePlay, (void*)*head, 0, &threadID);
if (thread)
{
// doing some work or just waiting
}
In one word (short answer), you need to call the BOOL TerminateThread(HANDLE hThread, DWORD dwExitCode); see microsoft docs in the link term_thread function and pass to it in the hThread param the return thread from CreateThread function in your case it is thread
for long answer
consider the thread function ThreadRoutine below:
#include <windows.h>
DWORD WINAPI ThreadRoutine(void* data) {
/*Creates a thread to execute within the virtual address space of the calling process.
this function will be passed later as a functio pointer to CreateThread which will be the the application-defined function to be executed by the thread.*/
return 0;
}
Now this is the CreateThread function from microsoft_docs
HANDLE CreateThread(
LPSECURITY_ATTRIBUTES lpThreadAttributes,
SIZE_T dwStackSize,
LPTHREAD_START_ROUTINE lpStartAddress,
__drv_aliasesMem LPVOID lpParameter,
DWORD dwCreationFlags,
LPDWORD lpThreadId
);
Function arguments
lpThreadAttributes: If lpThreadAttributes is NULL, the handle cannot be inherited by child processes.
dwStackSize: 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.
**lpStartAddress**:
A pointer to the application-defined function to be executed by the thread. This pointer represents the starting address of the thread. in our case its the ThreadRoutine.
lpParameter: A pointer to a variable to be passed to the thread. we can pass in void* what ever we like to pass since its a generic pointer.
dwCreationFlags: The flags that control the creation of the thread.
lpThreadId: 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.
Killing the thread we have created:
BOOL TerminateThread(HANDLE hThread, DWORD dwExitCode);
TerminateThread is used to cause a thread to exit. When this occurs, the target thread has no chance to execute any user-mode code. DLLs attached to the thread are not notified that the thread is terminating. The system frees the thread's initial stack.
If the function succeeds, the return value is nonzero.
If the function fails, the return value is zero.
So after reviewing all CreateThread arguments, we will use the the form below:
int main() {
HANDLE t_thread = CreateThread(NULL, 0, ThreadRoutine, NULL, 0, NULL);
if (t_thread ) {
// Optionally do stuff, such as wait on the thread or ...
/*After some time lets kill or terminate the thread we have created*/
BOOL re_term =TerminateThread(t_thread , DWORD dwExitCode);
if(re_term == 0){ //failed
/*maybe you should call GetLastError function*/
}
else{
/*killed successefully*/
}
}
return 0;
}

How to execute threads in a DLL in C

I created a DLL that is running 3 worker threads, and the main thread is in a loop waiting for the threads to complete. The threads get created, but no execution to the threads is done.
I have tried setting MessageBox functions inside the function that gets created with CreateThread() but the box does not appear. I have also tried to debug and the return value from CreateThread() is valid so the thread gets created.
BOOL WINAPI DllMain() {
main();
return 1;
}
int main() {
HANDLE h1, h2, h3;
h1 = CreateThread(first)...
h2 = CreateThread(second)...
h3 = CreateThread(third)...
WaitForSingleObject(h3, INFINITE);
return 1;
}
first() {
MessageBoxA("print some stuff");
return;
}
I have included some pseudocode of what my layout looks like. I am unable to provide the real code due to the sensitivity of it. However this is what is happening. I use LoadLibrary in another project that loads this .DLL. The DLL gets loaded and DllMain is executed. It then calls my main function which creates 3 threads. Each thread is created. But what is inside of the thread does not execute.
EDIT:
// dllmain.cpp : Defines the entry point for the DLL application.
#include <Windows.h>
void mb() {
MessageBoxW(0, L"AAAAAAAAAAAAAAAAAAAAAAAAA", L"AAAAAAAAAAAAAAAAAAAAAAa", 1);
}
void create() {
HANDLE han;
DWORD threadId;
han = CreateThread(NULL, 0, mb, NULL, 0, &threadId);
han = CreateThread(NULL, 0, mb, NULL, 0, &threadId);
han = CreateThread(NULL, 0, mb, NULL, 0, &threadId);
}
BOOL APIENTRY DllMain() {
create();
return 1;
}
[MS.Docs]: DllMain entry point (emphasis is mine) states:
Calling functions that require DLLs other than Kernel32.dll may result in problems that are difficult to diagnose. For example, calling User, Shell, and COM functions can cause access violation errors, because some functions load other system components. Conversely, calling functions such as these during termination can cause access violation errors because the corresponding component may already have been unloaded or uninitialized.
[MS.Docs]: MessageBox function resides in User32.dll, so it's Undefined Behavior (meaning that in different scenarios, it might work, it might work faulty, or it might crash).
Also, as #RbMm noticed, WaitForSingleObject doesn't belong there. I'm not sure about CreateThread either (but I couldn't find any official doc to confirm / infirm it).
Just out of curiosity, could you add a printf("main called.\n"); in main, to see how many times it is called?
because in general case DLL can be unloaded, need add reference to DLL - for it will be not unloaded until thread, which use it code executed. this can be done by call GetModuleHandleEx - increments the module's reference count unless GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT is specified. when thread exit - we dereference DLL code by call FreeLibraryAndExitThread. wait for all threads exit in most case not need. so code, inside dll can be next
ULONG WINAPI DemoThread(void*)
{
MessageBoxW(0, L"text", L"caption", MB_OK);
// dereference dlll and exit thread
FreeLibraryAndExitThread((HMODULE)&__ImageBase, 0);
}
void someFnInDll()
{
HMODULE hmod;
// add reference to dll, because thread will be use it
if (GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, (PCWSTR)&__ImageBase, &hmod))
{
if (HANDLE hThread = CreateThread(0, 0, DemoThread, 0, 0, 0))
{
CloseHandle(hThread);
}
else
{
// dereference dll if thread create fail
FreeLibrary(hmod);
}
}
}
wait inside dll entry point is wrong, because we hold here process wide critical section. if we wait for thread exit - this wait always deadlock - thread before exit (and start) try enter this critical section, but can not because we wait for him here. so we hold critical section and wait for thread(s), but threads(s) wait when we exit from this critical section. deadlock

WINAPI CreateThread C not always launch function

I'm writing a C program.
For thread I use the WINAPI library.
But sometimes the CreateThread function don't launch the function associate.
I used the WaitForSingleObject function with INFINITE param to let my thread start but he never start
The GetLastError functions return always 0,so I don't know where is my mistake
The merge function is call when GTK button is press.
Below you will find my code
void merge(GtkWidget *wiget, gpointer data){
HANDLE thread;
FtpLogin *login = (FtpLogin *) data;
thread = CreateThread(NULL, 0, mergeThread, login, 0, NULL);
printf("%ld", GetLastError());
WaitForSingleObject(thread, INFINITE);
if(thread == NULL)
puts("error");
}
DWORD WINAPI mergeThread( LPVOID lpParam )
{
puts("Thread start");
return 0;
}
Thanks for your help
The C run-time library needs some per-thread initialization. CreateThread(), which knows nothing about the C RTL, doesn't perform that.
Instead of CreateThread(), use _beginthreadex(). It's declared in <process.h>.
According to this page, GTK is not thread safe. Anything that interacts with the GUI inside your mergeThread function can have unexpected results.
Please refer to the link I provided for more information about multithreaded GTK applications to see how to use GDK instead.

Resources