KALYAN
KALYAN

Reputation: 93

How to create a thread in C program

I am tryin to create a thread using CreateThread() function and execute simple addition function in that thread. I wrote some code . But the thread is not being initiated any way.

Can you please help me in correcting the code

I have gone through MSDN for createthread function

#include <stdio.h>

#include <windows.h>
#include <tlhelp32.h>
#include <tchar.h>
#include <strsafe.h>

DWORD WINAPI ThreadFunc(LPVOID lpParam){
     int a=1;
     int b=2; 
     int c;
     c = a+b;
     printf("%d",c);
     return 0;
}

int main(void) 
{
    DWORD myThreadId;
    HANDLE THread_handle;
    printf("\n I am here inmain");
    THread_handle = CreateThread(NULL,0, ThreadFunc, NULL,0,&myThreadId);
    if (THread_handle == NULL) 
    {
        printf(TEXT("CreateThread"));
        //ExitProcess(3)
     }
    printf("I close\n");
    CloseHandle(THread_handle);
    return 0; 
}

Upvotes: 0

Views: 165

Answers (1)

selbie
selbie

Reputation: 104464

Your program is likely exiting before the thread you created in main has a chance to finish. Hence, the thread never had a chance to finish and print the result.

Prior to the CloseHandle call, add a WaitForSingleObject call. This will force the code in main to wait for the thread to complete.

    printf("I wait\n");
    WaitForSingleObject(THread_handle, INFINITE);

    printf("I close\n");
    CloseHandle(THread_handle);


    return 0; 
}

Further, make sure you flush the output in your thread as well. printf needs an end-of-line char.

Instead of this in ThreadFunc :

printf("%d",c);

Change it to this:

printf("%d\n",c);

Upvotes: 4

Related Questions