Click here to Skip to main content
15,119,637 members
Articles / Programming Languages / C++
Posted 16 Jul 2011

Tagged as


12 bookmarked

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
A very simple class that allows you to easily lock blocks of code from multi-threaded access.


This is nothing earth-shattering, just a little trick I've picked up, and like because it is rather slick.
Don't use this code unless you have to. As pointed out in the comments, STL already has this functionality. See std::mutex[^] and std::lock_guard[^].


In C# we use lock, without a second thought, to prevent simultaneous access from multiple threads. However in plan vanilla C++, you need to explicitly EnterCriticalSection and LeaveCriticalSection. Sometimes you may enter, but forget to leave. This tip takes care of that, and makes the code more compact.


The code is used as shown below:
 // All Lock classes using this will be mutually exclusive
static Section mySection;
void SomeFunction()
    // This block cannot be accessed simultaneously by multiple threads
        Lock lock(mySection);
        // any arbitrary code
    // end of locked block
Simple, isn't it? Basically what you do is, define a Section instance for each block of code that should be locked. This is usually a class member, but can easily be global too. Then wrap the portion of code to be locked in a block, and put a Lock instance at the top of it, passing the Section instance to it.

If you want several blocks that need to be locked from multiple threads, but not from each other, create the same number of Sections and use them in each block.


These are the contents of lock.h, which contains the classes Lock and Section.
// 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;
    // Constructor initializes critical section
    // Destructor deletes critical section
    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

    // Constructor saves user defined critical section and enters it
    Lock(Section & s) : section(s) { section.Enter(); }
    // Destructor leaves critical section
    ~Lock() { section.Leave(); }
That's it, quite simple (but see the disclaimer).

How it works

So what happens here? You veterans will find it quite obvious, but I'll explain it as easily as possible for others who don't.

First, Section just hides a regular CRITICAL_SECTION. Why hide it? Just to prevent unwary maintainers of our code from messing with it. The constructor and destructor initialize and delete the CRITICAL_SECTION respectively.

The Lock class does the actual locking. When we create an auto variable of this type in the code block, the constructor is called and enters the critical section defined in the Section passed to it. Leaving the scope of the block calls the destructor, which in turn calls LeaveCriticalSection.

Note that the Section field in Lock is a reference - this is to prevent the former's constructor from being called again, causing a double initialization of the same CRITICAL_SECTION.

See Also

MSDN page for related APIs - Critical Section Objects.


This is just the bare-bones code to illustrate the principle, with no exception handling. You'll have to add that as needed. Sample compiled cleanly on Visual C++ 2010 Express, other versions may give warnings.


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


About the Author

Japan Japan
No Biography provided

Comments and Discussions

GeneralA C#-like lock class for C++? Pin
Shao Voon Wong19-Mar-14 20:29
mvaShao Voon Wong19-Mar-14 20:29 
GeneralRe: A C#-like lock class for C++? Pin
Indivara22-Mar-14 4:02
professionalIndivara22-Mar-14 4:02 
SuggestionGreat short article! You should also check out... Pin
Chris La17-Mar-14 13:43
professionalChris La17-Mar-14 13:43 
I already have posted similar article not only critical section but other mutual exclusion schemes also.
I recommend you to check it out.
How to create a Simple Lock Framework for C++ Synchronization[^]

As others commented, this is not something new as I already wrote in my own article also.
But still it is good short explanation.
QuestionC++ has this Pin
William E. Kempf17-Mar-14 7:33
MemberWilliam E. Kempf17-Mar-14 7:33 
AnswerRe: C++ has this Pin
Oleg Artemenko17-Mar-14 9:47
MemberOleg Artemenko17-Mar-14 9:47 
GeneralRe: C++ has this Pin
William E. Kempf17-Mar-14 10:10
MemberWilliam E. Kempf17-Mar-14 10:10 
GeneralRe: C++ has this Pin
Indivara17-Mar-14 15:08
professionalIndivara17-Mar-14 15:08 
GeneralReason for my vote of 5 This may not be anything new, but it... Pin
Gordon Brandly19-Jul-11 9:19
MemberGordon Brandly19-Jul-11 9:19 
GeneralRe: Thanks! Pin
Indivara22-Jul-11 17:07
professionalIndivara22-Jul-11 17:07 
GeneralReason for my vote of 1 No new things.. Pin
Giri Ganji19-Jul-11 3:01
MemberGiri Ganji19-Jul-11 3:01 
GeneralRe: You're right, it isn't new; the full version's been in produ... Pin
Indivara22-Jul-11 17:07
professionalIndivara22-Jul-11 17:07 
GeneralReason for my vote of 5 Nice, clean and simple for beginners... Pin
John R. Shaw18-Jul-11 11:39
MemberJohn R. Shaw18-Jul-11 11:39 
GeneralRe: Thanks! Pin
Indivara22-Jul-11 17:05
professionalIndivara22-Jul-11 17:05 
QuestionI believe I've seen something very similar inside Win32++ Pin
Member 428961319-Jul-11 0:28
MemberMember 428961319-Jul-11 0:28 
GeneralRe: I believe I've seen something very similar inside Win32++ Pin
Indivara22-Jul-11 17:05
professionalIndivara22-Jul-11 17:05 
GeneralRe: I believe I've seen something very similar inside Win32++ Pin
Member 428961323-Jul-11 2:57
MemberMember 428961323-Jul-11 2:57 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.