#include <iostream>
#include <mutex>
#include <thread>
int gSharedData[2] = {1, 1};
std::mutex gMutex;
struct FunctionClass
{
void operator()()
{
int temp = 0;
for (int i = 0; i < 3; i++)
{
gMutex.lock();
gSharedData[0] = gSharedData[0] + 1;
gSharedData[1] = gSharedData[1] + 1;
std::cout << gSharedData[0] << " " << gSharedData[1] << " ";
gMutex.unlock();
}
}
};
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
Reference: https://isocpp.org/wiki/faq/cpp11-library-concurrency#std-mutex
Monday, September 11, 2017
C++11: Mutexes
C++11 added Mutexes. Here is an example:
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment