First, the header file windows. h must be included.
The following is a simple example: Start a new sub-thread execution function f () in the main function ().
# Include <windows. h>
# Include <iostream>
Using namespace std;
Void WINAPI f1 (LPVOID pvThread)
{
While (true)
{
Printf ("inside thread 1/n ");
Sleep (1000 );
}
}
Void WINAPI f2 (LPVOID pvThread)
{
While (true)
{
Printf ("inside thread 2/n ");
Sleep (2000 );
}
}
Int main ()
{
HANDLE hThread1 = CreateThread (NULL, 0, (LPTHREAD_START_ROUTINE) f1, NULL, 0, NULL );
HANDLE hThread2 = CreateThread (NULL, 0, (LPTHREAD_START_ROUTINE) f2, NULL, 0, NULL );
If (hThread1! = NULL)
{
WaitForSingleObject (hThread1, INFINITE );
CloseHandle (hThread1 );
}
If (hThread2! = NULL)
{
WaitForSingleObject (hThread2, INFINITE );
CloseHandle (hThread2 );
}
Return 0;
}
Where
If (hThread! = NULL)
{
Waitforsingleobject (hthread, infinite );
Closehandle (hthread );
}
This section is very important, which keeps the main thread. If this section does not exist, after the previous statement is executed, the main thread will exit without the sub-thread execution, and the sub-thread will also exit, which will not achieve the effect.
See here: http://topic.csdn.net/t/20020811/00/931486.html #