Professional Documents
Culture Documents
#multithreading
[[(thread)]] [[1.th.parameters]] [[2.th.&return]] [[3.th.lambda]] [[4.th.methods]]
[[5.mutex]] [[6.mutex.lock_guard]] [[7.Deadlock]] [[8.recursive_mutex]] [[9.
unique_lock]]
---
In multi-threaded applications, where multiple threads access and manipulate shared
resources concurrently, race conditions can occur. Race conditions happen when
multiple threads try to access and manipulate a shared resource simultaneously,
leading to unpredictable behavior and bugs in the program.
void shared_resource()
{
mtx.lock(); // acquire the lock
// do some work on the shared resource
std::cout << "Thread " << std::this_thread::get_id() << " is accessing the
shared resource\n";
mtx.unlock(); // release the lock
}
int main()
{
std::thread t1(shared_resource);
std::thread t2(shared_resource);
t1.join();
t2.join();
return 0;
}
```
# My Example
```cpp
#include <iostream>
#include <mutex>
#include <thread>
#include "SimpleTimer.h"
mutex mtx;
mtx.lock();
for (int i = 0; i < 5; ++i){
for (int i = 0; i < 10; i++) {
cout << ch;
this_thread::sleep_for(chrono::milliseconds(20));
}
cout << endl;
}
cout << endl;
mtx.unlock();
int main() {
SimpleTimer timer;
t1.join();
t2.join();
return 0;
}
```