Windows C + + waits for thread synchronization sample with each other

Source: Internet
Author: User

Windows C + + waits for thread synchronization sample with each other

Thread synchronization problems encountered in development can be abstracted into the following models:
1, the main thread continues to execute the premise is that the child thread variables have been initialized.
2, the child thread will continue to perform subsequent initialization operations after the main thread has finished executing.
Repeat to execute ... Until the communication is over.

As shown in the following:

Source code (VS2010 compile, run through)

#include "stdafx.h"#include <iostream>using namespace STD;#include <windows.h>Const Char* G_pszeventname ="Global/my_event";the name of the//event objectHANDLE g_hsettaskidevent = NULL;//Global event eventConst intg_imaxruncnt = -;//maximum number of runs./*** @brief: Simulates a thread function. * * @param: LPVOID pparam thread parameter, unused (transitive struct pointer, etc.) * * @return 0,ok; Other delegates exit unexpectedly. */UINT Recvdatathreadproc (LPVOID pparam) {cout<<"The Recvdatathreadproc () is running!"<< Endl;intnthreadcnt =0; while(Nthreadcnt < G_IMAXRUNCNT) {printf([Thread] the TaskId already setted! runcnt =%d\n ", nthreadcnt++); SetEvent (g_hsettaskidevent);//Trigger, the main thread can run.WaitForSingleObject (G_hsettaskidevent, INFINITE); }return 0;}/*** @brief: The main thread and the secondary thread run alternately. *****/int_tmain (intARGC, _tchar* argv[]) {//Start a processing threadDWORD dwThreadID =0; HANDLE Hrecvthread = CreateThread (NULL,//choose Default Security           0,//default Stack size(Lpthread_start_routine) &recvdatathreadproc,//routine to execute(LPVOID) Null//thread parameter              0,//immediately Run the thread&dwthreadid//thread Id);if(NULL = = Hrecvthread) {printf("CreateThread failed! Errcode:%d\n ", GetLastError ());return(1); }Else{printf("CreateThread ok!\n"); } closehandle (Hrecvthread);//1. Creating a Named Event object, automatically and initialized to a signal-free StateG_hsettaskidevent= CreateEvent (NULL, False, False, (LPCWSTR) (g_pszeventname));intIerrorcode = GetLastError ();if(error_already_exists = = Ierrorcode) {printf("[Process]createevent () The object is already exist!\n"); }Else if(NULL = = g_hsettaskidevent) {printf("[Process] CreateEvent () Error, Errorcode:%d\n", Ierrorcode); }Else{printf("[Process] CreateEvent () success!\n"); }unsigned intnruncnt =0; while(Nruncnt < G_IMAXRUNCNT) {BOOLBrunnext =false;//Initial to False, you cannot perform the following operation.   //wait for the signal to triggerDWORD Dwrst = WaitForSingleObject (g_hsettaskidevent, INFINITE);Switch(Dwrst) { CaseWAIT_OBJECT_0://The process terminated.   printf("[Process]the state of the specified object is signaled.\n"); Brunnext =true; Break; CaseWait_timeout://The process did not terminate within the given milliseconds.   printf("[Process]the time-out interval elapsed, and the object ' s state is nonsignaled.\n"); Break; CaseWait_failed://Bad call to function (invalid handle?)   printf("[Process]wait_failed, Errcode:%d\n", GetLastError ()); Break; }//end Switch  ///The following operation can be performed after the main thread is run.  if(Brunnext) {printf([Process] the process () Next can running!, running cnt =%d\n ", nruncnt++); } SetEvent (G_hsettaskidevent); } closehandle (G_hsettaskidevent);return 0;}

The essence is Abstract: event synchronization mechanism. The train ticket model is basically exactly the same as the Sunxin tutorial.

2014-3-20 pm23:47 at home in front of the bed

Ming Yi World
Reprint please indicate source, original address: http://blog.csdn.net/laoyang360/article/details/45646151
If you feel this article is helpful, please click on the ' top ' support, your support is I insist on writing the most power, thank you!

Windows C + + waits for thread synchronization sample with each other

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.