📅  最后修改于: 2023-12-03 14:59:45.091000             🧑  作者: Mango
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.
There are several types of locks available in C++:
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.
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.