Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a new thread (C, Windows)

OK, I'm a bit confused here. The following code works:

HANDLE CreateSideThread()
{
    DWORD dwGenericThread;
    HANDLE hThread1 = CreateThread(NULL, 0, CallBackFunc, NULL, 0, &dwGenericThread);

    return hThread1;
}

int main()
{
    HANDLE Thread1;

    Thread1 = CreateSideThread();
    WaitForSingleObject(hThread1, INFINITE);

    SomeOtherFunction();

    return 0;
}

The program does other things but you get the idea. It basically creates a new thread and executes whatever it is in CallBackFunc (which is an endless loop that check db status). Now, if I remove WaitForSingleObject() then the program will not even try CallBackFunc once and execute SomeOtherFunction(). What's the point then of a thread? I mean, i'm confused here.

What I am trying to do is call that thread with the check for the database status and keep that thread going while I continue with my program, calling other functions.

What am I doing wrong? Please post a sample snippet.

Thanks

like image 896
wonderer Avatar asked Mar 01 '23 07:03

wonderer


1 Answers

Without the WaitForSingleObject, your call to SomeOtherFunction() probably returns quickly enough for the program to exit before the new thread even gets a chance to run once.

When a C program returns from its main() function, the runtime system calls exit() for you. This forcibly exits your program even if other threads are trying to run at the same time. This is in contrast to other languages like Java for example, where exiting the main thread will not exit the process until all other (non-daemon) threads have finished running too.

like image 138
Greg Hewgill Avatar answered Mar 08 '23 16:03

Greg Hewgill