Critical section encapsulation and use example

Source: Internet
Author: User

Salute to my boss!

 

This is actually a copy of my boss. In the server, multi-thread often requires the use of critical sections. To simplify code usage, the critical section is encapsulated as a cthreadlockhandle class. Through encapsulation, only one line of code is required for each resource in the critical section, in addition, as long as the object life cycle is determined, the resource in the critical section can be automatically released:

Header file:

// Thread_lock.h # ifndef thread_lock_head_file # define thread_lock_head_file # include <windows. h> ////////////////////////////////////// //////////////////////////////////////// key synchronization class cthreadlock {// variable definition PRIVATE: critical_section m_cslock; // critical zone variable // function definition public: // constructor inline cthreadlock () {:: initializecriticalsection (& m_cslock) ;}; // destructor inline ~ Cthreadlock () {:: deletecriticalsection (& m_cslock) ;}; // function public: // lock function inline void lock () {:: entercriticalsection (& m_cslock );}; // unlock function inline void unlock () {:: leavecriticalsection (& m_cslock );};}; //////////////////////////////////////// /// // lock handle class cthreadlockhandle {// variable definition PRIVATE: int m_nlockcount; // lock count cthreadlock * m_pthreadlock; // lock the object // Function Definition publi C: // constructor cthreadlockhandle (cthreadlock * pthreadlock, bool bautolock = true); // destructor virtual ~ Cthreadlockhandle (); // function public: // lock function void lock (); // unlock function void unlock (); // int inline getlockcount () {return m_nlockcount ;};}; # endif

Source file:

// Thread_lock.cpp programed by Sany // 2014.9.2 // callme: [email protected] # include "thread_lock.h" # include <assert. h> ////////////////////////////////////// //////////////////////////////////////// secure synchronization Lock handle // constructor cthreadlockhandle:: cthreadlockhandle (cthreadlock * pthreadlock, bool bautolock) {assert (pthreadlock! = NULL); m_nlockcount = 0; m_pthreadlock = pthreadlock; If (bautolock) Lock (); return;} // destructor cthreadlockhandle ::~ Cthreadlockhandle () {While (m_nlockcount> 0) Unlock (); // automatically unlock after the lifecycle ends} // lock function void cthreadlockhandle: Lock () {// check status assert (m_nlockcount> = 0); Assert (m_pthreadlock! = NULL); // Lock Object m_nlockcount ++; m_pthreadlock-> lock ();} // unlock function void cthreadlockhandle: Unlock () {// check status assert (m_nlockcount> 0); Assert (m_pthreadlock! = NULL); // unlock status m_nlockcount --; m_pthreadlock-> unlock ();}

 

After encapsulation of this class, it takes only two steps to implement thread synchronization using the critical section:

1. initialize a global cthreadlock object to prepare for subsequent calls.

2. When a critical zone is required, a local variable cthreadlockhandle is declared in the scope. When the lifecycle ends, resources in the critical zone are automatically released.

 

Example:

# Include <stdio. h> # include <windows. h> # include <process. h> # include "thread_lock.h" const int asize = 10; char szarr [asize + 1] ={}; cthreadlock threadlock; // declare the global variable unsigned _ stdcall threadfunc1 (void *) {cthreadlockhandle lockhandle (& threadlock); // you need to use the critical section to declare a variable of the cthreadlockhandle type, its lifecycle is automatically unlocked for (int s = 0; S <asize; s ++) {szarr [s] = 'a'; sleep (1 );} return 0;} unsigned _ stdcall threadfunc2 (void *) {cthreadlockhandle lockhandle (& threadlock); // you need to use the critical section to declare a variable of the cthreadlockhandle type, its life cycle ends automatically unlocked for (int s = 0; S <asize; s ++) {szarr [aSize-1-s] = 'B'; sleep (1 );} return 0;} int main () {memset (szarr, 0, sizeof (szarr); handle handle1 = (handle) _ beginthreadex (null, 0, threadfunc1, null, 0, 0); handle handle2 = (handle) _ beginthreadex (null, 0, threadfunc2, null, 0, 0); waitforsingleobject (handle1, infinite); waitforsingleobject (handle2, infinite ); printf ("% s \ n", szarr); closehandle (handle1); closehandle (handle2); Return 0 ;}

 

If it is called in a class, declare the cthreadlock object as a private or protected member:

Class threadtest {protected: static cthreadlock m_threadlock; // thread lock public: static unsigned _ stdcall threadfunction (void * pthreaddata);}; unsigned _ stdcall threadtest: threadfunction (void * pthreaddata) {cthreadlockhandle lockhandle (& m_threadlock); // automatically unlock after the lifecycle ends // dosomething return 0 ;}

Appendix: http://www.cnblogs.com/userinterface/archive/2005/04/27/146137.html good thread synchronization article

Critical section encapsulation and use example

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.