C++11 added a timed_mutex template class that allows you to recursively obtain a lock by a single thread. Here is an example:
#include <iostream>
#include <mutex>
#include <thread>
int gSharedData[2] = {1, 1};
std::recursive_mutex gRecursiveMutex;
void updateData()
{
gRecursiveMutex.lock();
gSharedData[0] = gSharedData[0] + 1;
gRecursiveMutex.lock();
gSharedData[1] = gSharedData[1] + 1;
gRecursiveMutex.lock();
std::cout << gSharedData[0] << " " << gSharedData[1] << " ";
gRecursiveMutex.unlock();
gRecursiveMutex.unlock();
gRecursiveMutex.unlock();
}
struct FunctionClass
{
void operator()()
{
int temp = 0;
for (int i = 0; i < 3; i++)
{
updateData();
}
}
};
int main()
{
std::thread t1{FunctionClass()};
std::thread t2{FunctionClass()};
std::thread t3{FunctionClass()};
t1.join();
t2.join();
t3.join();
std::cout << std::endl;
return 0;
}
// Output: 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 10 10
No comments:
Post a Comment