Click here to Skip to main content
15,886,806 members
Articles / Programming Languages / C++

A C#-like lock class for C++

Rate me:
Please Sign up or sign in to vote.
4.46/5 (8 votes)
17 Mar 2014CPOL2 min read 40K   95   12  
A very simple class that allows you to easily lock blocks of code from multi-threaded access.
// Lock.h
#pragma once 
 
#include <windows.h>
 
class Lock; // Forward declaration

// Class to encapsulate CRITICAL_SECTION 
class Section
{
    // Actual critical section that will do the locking
    CRITICAL_SECTION criticalSection;
 
public:
    // Constructor initializes critical section
    Section()
    {
        InitializeCriticalSection(&criticalSection);
    }
 
    // Destructor deletes critical section
    ~Section()
    {
        DeleteCriticalSection(&criticalSection);
    }
 
private:
    friend Lock; // Allow Lock class to access Enter and Leave methods

    // Methods to enter and leave the critical section defined by the field above
    void Enter() { EnterCriticalSection(&criticalSection); }
    void Leave() { LeaveCriticalSection(&criticalSection); }
};
 
// Class that does the locking
class Lock
{
    Section & section; // Section defined by user will be saved here

public:
    // Constructor saves user defined critical section and enters it
    Lock(Section & s) : section(s) { section.Enter(); }
 
    // Destructor leaves critical section
    ~Lock() { section.Leave(); }
};

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Engineer
Japan Japan
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions