Creating the Windows thread - a very simple C program example

 

 

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows Xp Pro SP2

Target platform: none, just for learning and fun

Header file: Standard and Windows

Additional library: Windows Platform SDK

Additional project setting: Set project to be compiled as C

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C Code (/TC)

Other info: non-CLR or unmanaged.

To do: Creating the Windows thread using C code sample

To show: Windows thread and process operation

 

 

 

 

// For WinXp as a target, change accordingly

#define _WIN32_WINNT 0x0501

 

#include <windows.h>

#include <stdio.h>

#include <conio.h>

 

DWORD WINAPI MyThreadFunction(LPVOID lpParam)

{

printf("The parameter: %u.\n", *(DWORD*)lpParam);

return 0;

}

 

int main(void)

{

DWORD dwThreadId, dwThrdParam = 1;

HANDLE hThread;

 

hThread = CreateThread(

NULL, // default security attributes

0, // use default stack size

MyThreadFunction, // thread function

&dwThrdParam, // argument to thread function

0, // use default creation flags

&dwThreadId); // returns the thread identifier

 

printf("The thread ID: %d.\n", dwThreadId);

 

// Check the return value for success. If something wrong...

if (hThread == NULL)

printf("CreateThread() failed, error: %d.\n", GetLastError());

//else, gives some prompt...

else

printf("It seems the CreateThread() is OK lol!\n");

if (CloseHandle(hThread) != 0)

printf("Handle to thread closed successfully.\n");

return 0;

}

 

Output example:

 

The thread ID: 3076.

The parameter: 1.

It seems the CreateThread() is OK lol!

Handle to thread closed successfully.

Press any key to continue . . .

 

 

C and C++ Programming Resources | C & C++ Code Example Index