Thread synchronization-critical Section objects

Source: Internet
Author: User

1. Critical section Object

A critical section is a method that guarantees that only one thread can access the data at a certain time. In the process of using it, it is necessary to provide each thread with a shared critical section object, which can access the protected data regardless of which thread occupies the critical section object, while the other thread waits until the critical section object is released by the thread, and the other thread can take over the critical section. To access the shared data.

2, the main function method

InitializeCriticalSection (&CS);//Initialize critical section entercriticalsection (&CS);//Enter critical section leavecriticalsection (&CS) ;//Leave critical section deletecriticalsection (&CS);//Delete critical section


3. code example
Global variable declaration:

int g_count1 = 0;int G_count2 = 0; BOOL g_bcontinue = FALSE; Critical_section G_cs;

Thread handler functions:
UINT _stdcall ThreadFunc (LPVOID)//thread handling function {:: EnterCriticalSection (&g_cs);//Enter while (g_bcontinue) {G_count1++;g_ Count2++;}::leavecriticalsection (&g_cs);//Leave return 0;}
Call Function:

void Cmultithreadsyncdlg::onbnclickedbutton1 () {//TODO: Add control notification Handler code here G_COUNT1 = G_count2 = 0;::i Nitializecriticalsection (&g_cs);//Initialize//g_sync_flag = Flag_critical;g_bcontinue = TRUE; UINT uId; HANDLE h[2];h[0] = (HANDLE):: _beginthreadex (NULL, 0, threadfunc, NULL, 0, &UID); h[1] = (HANDLE):: _beginthreadex (null , 0, ThreadFunc, NULL, 0, &uid);//wait for sleep (+), g_bcontinue = False;::waitformultipleobjects (2, H, TRUE, INFINITE);: : CloseHandle (H[0]);:: CloseHandle (H[1]);::D eletecriticalsection (&G_CS);//delete//cstring str;//str. Format (_t ("g_count1 =%d\r\ng_count2 =%d\r\n"), G_count1, G_count2);//m_fact. SetWindowText (str);}




Thread synchronization-critical Section objects

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.