📜  c++ lock - C++ (1)

📅  最后修改于: 2023-12-03 14:59:45.091000             🧑  作者: Mango

C++ Lock

Introduction

In C++, locks are used to ensure the mutual exclusion of code execution for multiple threads accessing shared resources. This can prevent race conditions and other concurrency issues.

Types of Locks

There are several types of locks available in C++:

  • std::mutex: A basic mutual exclusion lock. Only one thread can hold the lock at a time. If another thread tries to acquire the lock, it will be blocked until the lock becomes available.
  • std::timed_mutex: A variation of std::mutex that provides a timeout mechanism. If a lock cannot be acquired within a specified time, it will return an error instead of blocking indefinitely.
  • std::recursive_mutex: A type of lock that can be locked recursively by the same thread. This can be useful in situations where a thread needs to hold a lock while calling a function that also requires the same lock.
  • std::shared_mutex: A read/write lock that allows multiple threads to hold a lock simultaneously for reading, but only one thread can hold the lock for writing. This can be useful in situations where multiple threads need to read the same resource, but only one thread can modify it at a time.
  • std::unique_lock: A wrapper around a mutex that provides additional features, such as the ability to lock and unlock the mutex at different times, and the ability to transfer ownership of the lock to another thread.
Example

Here is an example of using std::mutex to lock a shared resource:

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

std::mutex mtx;
int counter = 0;

void incrementCounter() {
    for (int i = 0; i < 1000000; i++) {
        mtx.lock();
        counter++;
        mtx.unlock();
    }
}

int main() {
    std::thread t1(incrementCounter);
    std::thread t2(incrementCounter);
    t1.join();
    t2.join();
    std::cout << "Counter value: " << counter << std::endl;
    return 0;
}

In this example, two threads are created that call the incrementCounter() function, which increments the shared variable counter 1,000,000 times. The mtx mutex is used to ensure that only one thread can modify the counter variable at a time. Without the mutex, the results of the program would be unpredictable due to race conditions.

Conclusion

Locks are an essential part of multithreaded programming in C++. It is important to choose the right type of lock for a given situation to ensure optimal performance and avoid issues like deadlocks or livelocks.