Multithreading using Windows APIs-Example of principles

Source: Internet
Author: User

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 #

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.