Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons
  • Teach on BraveProgrammer

© 2026 BraveProgrammer. All rights reserved.

Lesson 39: Mutexes and Locks (std::mutex | C++ Course lesson | BraveProgrammer
  1. Courses
  2. /
  3. C++ Course

Lesson 39 of 45

·C++

Lesson 39: Mutexes and Locks (std::mutex, std::lock_guard)

11 min

Course progress87%

What you'll learn

Keep these ideas in mind as you work through the lesson.

4 points
  • Mutual exclusion primitives
  • RAII lock guards
  • Lock ordering and deadlock avoidance
  • C++17 `std::scoped_lock`

Mutexes and Locks (std::mutex, std::lock_guard)

Mutual exclusion primitives protect shared data from concurrent access. std::mutex provides low‑level lock/unlock operations, while RAII wrappers like std::lock_guard and std::unique_lock ensure the lock is released even if an exception is thrown.


Example: Protecting a shared counter with std::lock_guard

#include <thread>
#include <mutex>

int counter = 0;
std::mutex mtx;

void increment(int times) {
    for (int i = 0; i < times; ++i) {
        std::lock_guard<std::mutex> lock(mtx);
        ++counter;
    }
}

int main() {
    std::thread t1(increment, 1000);
    std::thread t2(increment, 1000);
    t1.join();
    t2.join();
    std::cout << \"Final counter: \" << counter << '\
';
    return 0;
}

std::unique_lock for more flexibility

std::unique_lock<std::mutex> lock(mtx, std::defer_lock);
// ... perform some work without holding the lock
lock.lock(); // acquire later
// critical section
lock.unlock(); // release early if needed

Tip: Prefer std::scoped_lock (C++17) when you need to lock multiple mutexes atomically.


<Alert type="info">Deadlocks occur when two threads acquire the same mutexes in opposite order. Use a consistent lock acquisition order or std::scoped_lock to avoid.

Make it stickPractice what you've learned1 quiz · 2 practical tests · Optional activities from C++ CourseBrowse activities
Previous lessonLesson 38: Threads (std::thread)Continue to lesson 40Lesson 40: Atomic Operations (std::atomic)Back to C++ Course curriculum