WINAPI CreateThread C not always launch function - c

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.

Related

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 can I call a Gtk API from another thread?

I've written a C program in which I implemented some threads to make polling. When something happens in the thread I have to modify some Widgets created in main function.
This program sometimes crashes when a thread tries to do an operation on a Widget, for example simply calling the function gtk_widget_hide, and I discovered that's because I must not call any GTK API from another thread.
How can I do what I've described before avoiding any crashes? Is it possible, considering I need threads?
That's an example of what my code does
static GtkWidget* widget;
void check_user_action(){
while(!user_does_action){
g_sleep(1);
}
gtk_widget_hide(main_widget);
}
void main(){
widget = //I skip widget creation
gtk_widget_show_all(widget);
g_thread_new("check_user_action", check_user_action, NULL);
//do something else
}
That's only an example, but assume the only way I have to check_user_action is with polling.
For your snippet you can pass the task to your main thread:
gboolean my_hide_func(gpointer user_data)
{
gtk_widget *widget = (gtk_widget*) user_data;
gtk_widget_hide(widget);
return FALSE;
}
void check_user_action(){
while(!user_does_action){
g_sleep(1);
}
g_idle_add(my_hide_func, main_widget);
}
This will enqueue a request to call that function in the queue for the main thread running your GTK application.

How to use close handler in winapi if you need to clean up everything in another thread?

I'm creating a thread for my game. But I found, that if close button is pressed, or the task is killed I cannot properly finish the work, deallocating all the resources I needed inside the program.
I found that Close handler exists, but the example given is an unknown magic to me, because I need to create something similar in ANSI-C.
static BOOL CloseHandler(DWORD evt)
{
if (evt == CTRL_CLOSE_EVENT)
{
m_bAtomActive = false;
// Wait for thread to be exited
std::unique_lock<std::mutex> ul(m_muxGame);
m_cvGameFinished.wait(ul);
}
return true;
}
I know that Winapi has Mutex and conditional variables, but I do not know anything about std::atomic equivalent.
I have this thread start function and inside thread function GameThread I have a regular bool variable m_bAtomActive checked now.
void Start(void* _self)
{
DWORD dwThreadID;
HANDLE hThread;
struct c_class* this = _self;
this->m_bAtomActive = true;
hThread = CreateThread(
NULL,
0,
&GameThread,
_self,
0,
&dwThreadID);
WaitForSingleObject(hThread, INFINITE);
}
I'm bad at threading, what should I do to properly finish the work of my game?
All the additional details will be provided in the comments or on the chat.
UPD: The first thing seems to be easy, it is solvable with this line inside close handler
if(Active)
InterlockedDecrement(&Active);
But the second and third is still under question. They might be created for the reason of CloseHandler killing the app before destruction, but I don't know for sure.

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

How to start a thread with _beginthreadex?

I read on stackoverflow that when using the Windows API to start a thread _beginthreadex() is preferred over CreateThread().
I am creating threads like this using CreateThread():
DWORD WINAPI ThreadFunc(void* data)
{
// code for the thread functionality.
}
HANDLE Multicast = CreateThread(NULL, 0, ThreadFunc, NULL, 0, NULL);
if (Multicast) { } // thread started successfully.
How do I do this with _beginthreadex() rather than CreateThread()?
Can anyone post an example?
_beginthreadex(NULL, 0, ThreadFunc, NULL,0,NULL);
should do the trick for you. You can ignore those additional parameters as most of those are optional.
The following SO links might be useful for you:
Windows threading: _beginthread vs _beginthreadex vs CreateThread C++
_beginthread vs CreateThread

Resources