The Windows threads operation and delay between threads 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: Demonstrate the Windows threads and time delay
To show: The Windows threads and processes operation
#include <windows.h>
#include <stdio.h>
#include <conio.h>
#include <process.h>
unsigned Counter;
unsigned __stdcall SecondThreadFunc(void* pArguments)
{
printf("In the second thread...\n");
while (Counter < 1000000)
Counter++;
_endthreadex(0);
return 0;
}
int main(int argc, char *argv[])
{
HANDLE hThread;
unsigned int threadID = 0;
printf("Creating second thread...\n");
// Create the second thread.
hThread = (HANDLE)_beginthreadex(NULL, 0, &SecondThreadFunc, NULL, 0, &threadID);
printf("The thread ID = %u.\n", threadID);
// Wait until second thread terminates. If you comment out the line below, Counter will not be correct because the thread has not
// terminated, and Counter most likely has not been incremented to 1000000 yet.
WaitForSingleObject(hThread, INFINITE);
printf("Counter should be 1000000; yes it is %u\n", Counter);
// Destroy the thread object.
if(CloseHandle(hThread) != 0)
printf("Handle to the thread closed successfully\n");
return 0;
}
Output example:
Creating second thread...
The thread ID = 2976.
In the second thread...
Counter should be 1000000; yes it is 1000000
Handle to the thread closed successfully
Press any key to continue . . .