C + + uses CriticalSection to implement thread synchronization instances _c languages

Source: Internet
Author: User

This article describes the C + + using CriticalSection method to implement thread synchronization, in the previous C + + thread synchronization case analysis based on the addition of four lines of code, the use of four functions:
EnterCriticalSection::D eletecriticalsection:: entercriticalsection:: LeaveCriticalSection At this time, the number printed out is equal.

The specific code is as follows:

#include "stdafx.h" 
#include <Windows.h> 
 
DWORD g_cnt1; 
DWORD G_cnt2; 
BOOL g_bcontinue = TRUE; 
Critical_section CS; 
 
DWORD WINAPI ThreadProc (__in lpvoid lpparameter) 
{ 
  :: EnterCriticalSection (&CS); 
  while (g_bcontinue) 
  { 
    g_cnt1++; 
    g_cnt2++ 
  } 
  :: LeaveCriticalSection (&CS); 
  return 0; 
} 
 
int _tmain (int argc, _tchar* argv[]) 
{ 
  HANDLE hthread[2]; 
  g_cnt1 = G_cnt2 = 0; 
  :: InitializeCriticalSection (&CS); 
 
  Hthread[0] =:: CreateThread (NULL, 0, threadproc, NULL, 0, NULL); 
  HTHREAD[1] =:: CreateThread (NULL, 0, threadproc, NULL, 0, NULL); 
 
  Sleep (1000); 
  G_bcontinue = FALSE; 
  :: WaitForMultipleObjects (2, Hthread, TRUE, INFINITE); 
  printf ("g_cnt1=%d\n", g_cnt1); 
  printf ("g_cnt2=%d\n", G_cnt2); 
 
  ::D eletecriticalsection (&CS);: 
 
  : CloseHandle (Hthread[0]);:: 
  CloseHandle (hthread[1]); 
  return 0; 
}

I hope this article will help you with the C + + program design.

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.