A small example of a Windows Thread

Source: Internet
Author: User

# Include <iostream> <br/> using namespace STD; <br/> # include "windows. H "<br/> extern DWORD winapi threadfunc (lpvoid); <br/> int main (INT argc, char * argv []) <br/>{</P> <p> DWORD threadid; <br/> cout <"test thread" <Endl; <br/> handle hthread = :: createthread (null, 0, threadfunc, 0, 0, & threadid); <br/> for (INT I = 0; I <10; I ++) <br/>{< br/> cout <Endl <"main thread" <I <Endl; <br/>}< br/> return 0; <br/>}< br/> DWORD winapi threadfunc (lpvoid) <br/>{< br/> int I = 0; <br/> while (true) <br/>{< br/> cout <"thread func" <I ++ <Endl; <br/>}< br/>}

 

Running result:

Test thread

Main thread func00

Thread funcmain thread 11

Thread func
2
Thread funcmain thread 32

Thread funcmain thread 43
Thread func
5

Main thread func46

Thread funcmain thread 75

Thread func
8 main thread
6 thread func
9

Main thread func710

Thread funcmain thread 118

Thread func
12 main thread
9 thread func
1. Press any key to continue...

 

 

This small example describes two points:

1. When the main thread ends, the thread also ends.

2 because cout writes data in a buffer zone, to ensure the correctness of the result, a critical section must be added for mutual exclusion.

Related Article

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.