# MutexProtected: A C++ Pattern for Easier Concurrency

DevFeed: [MutexProtected: A C++ Pattern for Easier Concurrency](<https://devfeed.tech/articles/mutexprotected-a-c-pattern-for-easier-concurrency-38361.md>)

Original publisher: [Read original article](<https://awesomekling.github.io/MutexProtected-A-C++-Pattern-for-Easier-Concurrency/>)

Author: Andreas Kling

Published: 2023-04-06T00:00:00Z

Content type: tutorial

Language: en

Sources: [Andreas Kling](<https://devfeed.tech/sources/andreas-kling.md>)

Topics: [C++](<https://devfeed.tech/topics/c-plus-plus.md>), [Concurrency](<https://devfeed.tech/topics/concurrency.md>), [Programming](<https://devfeed.tech/topics/programming.md>), [Code](<https://devfeed.tech/topics/code.md>), [Deadlock](<https://devfeed.tech/topics/deadlock.md>)

Tags: [c-plus-plus](<https://devfeed.tech/tags/c-plus-plus.md>), [callback](<https://devfeed.tech/tags/callback.md>), [class](<https://devfeed.tech/tags/class.md>), [concurrency](<https://devfeed.tech/tags/concurrency.md>), [cpp](<https://devfeed.tech/tags/cpp.md>), [locks](<https://devfeed.tech/tags/locks.md>), [mutex](<https://devfeed.tech/tags/mutex.md>), [programming](<https://devfeed.tech/tags/programming.md>), [serenityos](<https://devfeed.tech/tags/serenityos.md>), [technical](<https://devfeed.tech/tags/technical.md>), [type-system](<https://devfeed.tech/tags/type-system.md>)

## AI overview

This tutorial explains the MutexProtected pattern, which combines a mutex and protected data behind a callback-based C++ API. It compares manual locking in C with C++ RAII and the newer pattern, showing how the design reduces forgotten-lock errors and encodes the mutex-data relationship in the type system. It also notes that inconsistent ordering of multiple MutexProtected instances can still cause deadlocks.

## Source excerpt

In this post, we will discuss the challenges of programming with locks and how the C++ language offers some useful tools to make it easier. We will start with an example in C and then use C++ to improve upon it in steps. The example APIs are based on real-life APIs from the SerenityOS kernel.