Critical sections in multi-threading

Source: Internet
Author: User

The critical section is also called the critical code segment. Shared variables are used to read and write securely when sharing variables in multiple threads. The code is as follows:

Critical_section??? G_cssync?=? {};//critical section int??? G_idata?=?0;dword?? WINAPI?? Writethreadproc (Lpvoid?lpparameter) {//write thread while? 1) {Sleep (+); __try{entercriticalsection (&g_cssync); g_idata++;} __finally{leavecriticalsection (&g_cssync);}} return?0;} DWORD? WINAPI?? Readthreadproc (Lpvoid?lpparameter) {//Read thread while? true) {Sleep (+); __try{entercriticalsection (&g_cssync);//Enter critical section char?str[20]?=?{}; Itoa (G_IDATA,?STR,?10); TRACE (str);} __finally{leavecriticalsection (&g_cssync);//Leave the critical area}}return?0;} void? Ctestthreaddlg::onbnclickedbutton16 () {initializecriticalsectionandspincount (&g_cssync,?0x4000);// Initialize critical section DWORD?? threadid?=?0; HANDLE?? Hthread[2]?=? {};hthread[0]?=? CreateThread (null,?0,? ( Lpthread_start_routine) Writethreadproc,?????????????????????? Null? Create_suspended,?&threadid); hthread[1]?=? CreateThread (null,?0,? ( Lpthread_start_routine) Readthreadproc,?????????????????????? Null? Create_suspended,?&threadid); ResumeThread (Hthread[0]); ResumeThread (hthread[1]); WaitForMultipleObjects (2,?hthread,? TRUE,? INFINITE); CloseHandle (Hthread[0]); CloseHandle (hthread[1]);D eletecriticalsection (&g_cssync);//delete critical section}


Critical sections in multi-threading

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.