Table of Contents
? Basic usage: protect shared counters
✅ Output example:
?️ More recommended writing method: use std::lock_guard
? Key points summary:
? Tips: When to use mutex?
Home Backend Development C++ C mutex example

C mutex example

Aug 03, 2025 am 08:43 AM
c++ mutex

std::mutex is used to protect shared resources to prevent data competition. In the example, the automatic locking and unlocking of std::lock_guard is used to ensure multi-thread safety; 1. Use std::mutex and std::lock_guard to avoid the abnormal risks brought by manual management of locks; 2. Shared variables such as counters must be protected with mutex when modifying multi-threads; 3. RAII-style lock management is recommended to ensure exception safety; 4. To avoid deadlocks, multiple locks need to be acquired in a fixed order; 5. Any multi-threaded scenario to access shared resources should use mutex synchronization, and the final program correctly outputs Expected: 10000 and Actual: 10000.

C mutex example

In C multi-threaded programming, std::mutex is an important tool used to protect shared resources and prevent multiple threads from simultaneously accessing data. Here is a simple example of using std::mutex , showing how to use it to safely modify shared variables in multiple threads.

C mutex example

? Basic usage: protect shared counters

 #include <iostream>
#include <thread>
#include <mutex>
#include <vector>

std::mutex mtx; // Define a mutex int counter = 0; // Shared resource: Counter void increment(int n) {
    for (int i = 0; i < n; i) {
        mtx.lock(); // Lock counter; // Access shared resources (critical area)
        mtx.unlock(); // Unlock}
}

int main() {
    const int num_threads = 10;
    const int inc_per_thread = 1000;

    std::vector<stdhread> threads;

    // Create multiple threads for (int i = 0; i < num_threads; i) {
        threads.emplace_back(increment, inc_per_thread);
    }

    // Wait for all threads to complete for (auto& t : threads) {
        t.join();
    }

    std::cout << "Expected: " << num_threads * inc_per_thread << std::endl;
    std::cout << "Actual: " << counter << std::endl;

    return 0;
}

✅ Output example:

 Expected: 10000
Actual: 10000

Without mutex , the actual result is likely to be less than 10000, because multiple threads may read and write counter at the same time, resulting in race conditions.


Manually calling lock() and unlock() is prone to errors (such as exceptions that cause unlock to not be executed). It is recommended to use RAII -style std::lock_guard to automatically manage the life cycle of locks.

C mutex example
 void increment(int n) {
    for (int i = 0; i < n; i) {
        std::lock_guard<std::mutex> lock(mtx); // Automatic locking, automatic unlocking of counter after the scope ends;
    }
}

This ensures that the lock is released correctly even if an exception occurs in the critical area.


? Key points summary:

  • std::mutex is used to protect shared data.
  • Never do time-consuming or potentially throw exceptions when holding a lock.
  • Use std::lock_guard or std::unique_lock instead of manual lock/unlock .
  • Avoid deadlocks: Multiple locks should be obtained in a fixed order.

? Tips: When to use mutex?

When you have multiple threads:

C mutex example
  • Read and write the same global variable
  • Modify the same container (such as std::vector , std::map )
  • Shared I/O resources such as writing logs and files

You need to use mutex to synchronize access.


Basically that's it. It is simple but easy to ignore details, and using lock_guard is the key.

The above is the detailed content of C mutex example. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1505
276
C   find in vector example C find in vector example Aug 02, 2025 am 08:40 AM

The most common method of finding vector elements in C is to use std::find. 1. Use std::find to search with the iterator range and target value. By comparing whether the returned iterator is equal to end(), we can judge whether it is found; 2. For custom types or complex conditions, std::find_if should be used and predicate functions or lambda expressions should be passed; 3. When searching for standard types such as strings, you can directly pass the target string; 4. The complexity of each search is O(n), which is suitable for small-scale data. For frequent searches, you should consider using std::set or std::unordered_set. This method is simple, effective and widely applicable to various search scenarios.

C   char array to string example C char array to string example Aug 02, 2025 am 05:52 AM

The answer is: Use the std::string constructor to convert the char array to std::string. If the array contains the intermediate '\0', the length must be specified. 1. For C-style strings ending with '\0', use std::stringstr(charArray); to complete the conversion; 2. If the char array contains the middle '\0' but needs to convert the first N characters, use std::stringstr(charArray,length); to clearly specify the length; 3. When processing a fixed-size array, make sure it ends with '\0' and then convert it; 4. Use str.assign(charArray,charArray strl

C   endianness check example C endianness check example Jul 30, 2025 am 02:30 AM

The system endianness can be detected by a variety of methods, the most commonly used is the union or pointer method. 1. Use a union: Assign uint32_t to 0x01020304, if the lowest address byte is 0x04, it is a small endian, and if it is 0x01, it is a big endian; 2. Use pointer conversion: Assign uint16_t to 0x0102, read the byte order through the uint8_t pointer, [0]==0x02 and [1]==0x01 is a small endian, otherwise it is a big endian; 3. Compilation-time detection: define the constexpr function to determine whether the (char)&int variable is 1, and combine ifconstexpr to determine the endian order during the compilation period; 4. Runtime macro encapsulation: use (char*)&amp

What are the correct launch.json settings for debugging a C   application with GDB on Linux? What are the correct launch.json settings for debugging a C application with GDB on Linux? Aug 04, 2025 am 03:46 AM

TodebugaC applicationusingGDBinVisualStudioCode,configurethelaunch.jsonfilecorrectly;keysettingsincludespecifyingtheexecutablepathwith"program",setting"MIMode"to"gdb"and"type"to"cppdbg",using"ex

C   mutex example C mutex example Aug 03, 2025 am 08:43 AM

std::mutex is used to protect shared resources to prevent data competition. In the example, the automatic locking and unlocking of std::lock_guard is used to ensure multi-thread safety; 1. Using std::mutex and std::lock_guard can avoid the abnormal risks brought by manual management of locks; 2. Shared variables such as counters must be protected with mutex when modifying multi-threads; 3. RAII-style lock management is recommended to ensure exception safety; 4. Avoid deadlocks and multiple locks in a fixed order; 5. Any scenario of multi-thread access to shared resources should use mutex synchronization, and the final program correctly outputs Expected:10000 and Actual:10000.

C   erase from vector while iterating C erase from vector while iterating Aug 05, 2025 am 09:16 AM

If it is iterating when deleting an element, you must avoid using a failed iterator. ①The correct way is to use it=vec.erase(it), and use the valid iterator returned by erase to continue traversing; ② The recommended "erase-remove" idiom for batch deletion: vec.erase(std::remove_if(vec.begin(),vec.end(), condition), vec.end()), which is safe and efficient; ③ You can use a reverse iterator to delete from back to front, the logic is clear, but you need to pay attention to the condition direction. Conclusion: Always update the iterator with the erase return value, prohibiting operations on the failed iterator, otherwise undefined behavior will result.

What is Succinct (PROVE Coin)? How to operate? PROVE Token Economy and Price Forecast What is Succinct (PROVE Coin)? How to operate? PROVE Token Economy and Price Forecast Aug 06, 2025 pm 06:42 PM

Directory What is Succinct (PROVE) Who created Succinct (PROVE)? Which venture capital supports Succinct (PROVE)? How Succinct (PROVE) works SP1zkVM and Prover network OPSuccinct technology Cross-chain verification PROVE token economics token details Token allocation token utility potential token holders PROVE token price prediction PROVE token pre-market trading activities community prediction of PROVE token price Why choose Succinct? Succ

C   Boost library example C Boost library example Jul 30, 2025 am 01:20 AM

Install the Boost library, 2. Write code for DNS resolution using Boost.Asio, 3. Compile and link the boost_system library, 4. Run the program to output the IP address parsed by www.google.com; this example shows how Boost.Asio simplifies network programming in C, implements cross-platform, type-safe synchronous DNS queries through io_context and tcp::resolver, and supports IPv4 and IPv6 address resolution, and finally prints all resolution results.

See all articles