Windows API one-day training (46) entercriticalsection and leavecriticalsection Functions

Source: Internet
Author: User
When multiple threads operate on the same data, they generally need to access the data in order. Otherwise, data may become disordered and data cannot be controlled and becomes a random variable. To solve this problem, we need to introduce mutex variables so that each thread can access the variables in sequence. In this way, you need to use Entercriticalsection And Leavecriticalsection Function. Function Entercriticalsection And Leavecriticalsection The statement is as follows: Winbaseapi Void Winapi Entercriticalsection ( _ Inout lpcritical_section lpcriticalsection ); Winbaseapi Void Winapi Leavecriticalsection ( _ Inout lpcritical_section lpcriticalsection ); Lpcriticalsection Is to create a critical area object. An example of calling a function is as follows: #001 ccaiwinmsg: ccaiwinmsg (void) #002 { #003 m_hbtn = NULL; #004 m_ncount = 0; #005 #006 m_pthreada = NULL; #007 m_pthreadb = NULL; #008 #009 // #010 initializecriticalsection (& m_cscount ); #011 #012} #013 #014 ccaiwinmsg ::~ Ccaiwinmsg (void) #015 { #016 deletecriticalsection (& m_cscount ); #017} #018 The 10 A row is an object that creates a critical section. The 16 A row is an object that deletes a critical section. #001 // #002 // Window message processing class. #003 // Cai junsheng 2007/08/13 #004 // #005 class ccaiwinmsg: #006 public ccaiwin #007 { #008 public: #009 ccaiwinmsg (void ); #010 virtual ~ Ccaiwinmsg (void ); #011 #012 // Thread operation function. #013 int addcount (void) #014 { #015 // #016 entercriticalsection (& m_cscount ); #017 int nret = m_ncount ++; #018 leavecriticalsection (& m_cscount ); #019 #020 return nret; #021} In the Function Addcount Calling Entercriticalsection And Leavecriticalsection To mutex access variables M_ncount . With the above method, multiple threads can access the same variables in sequence.
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.