Mutex and Atomics
To protect value with a simple mutex.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
#include <iostream> #include <thread> #include <mutex> long sum{0}; std::mutex m_tex{}; void calcSum(int start, int end){ for(int x=start; x <= end; x++ ){ m_tex.lock(); sum += x; m_tex.unlock(); } } int main() { calcSum(0, 10000000); std::cout << "Normal Calculation " << sum << std::endl; sum = 0; std::thread t1(calcSum, 0, 5000000); std::thread t2(calcSum, 5000001, 10000000); t1.join(); t2.join(); std::cout << "Threat Calculation " << sum << std::endl; } |
The other way is using unique_lock but it locks threat critically
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
#include <iostream> #include <thread> #include <mutex> long sum{0}; std::mutex m_tex{}; void calcSum(int start, int end){ std::unique_lock<std::mutex> unilock(m_tex); for(int x=start; x <= end; x++ ){ sum += x; } } int main() { calcSum(0, 10000000); std::cout << "Normal Calculation " << sum << std::endl; sum = 0; std::thread t1(calcSum, 0, 5000000); std::thread t2(calcSum, 5000001, 10000000); t1.join(); t2.join(); std::cout << "Threat Calculation " << sum << std::endl; } |
New Memory model Atomic
Atomic brings us a secure model to reach data on memory. However, it is slower than the simple mutex operation, atomic types make us sure about memory sharing.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
#include <iostream> #include <thread> #include <atomic> std::atomic<long> sum{0}; void calcSum(int start, int end){ for(int x=start; x <= end; x++ ){ sum += x; } } int main() { calcSum(0, 10000000); std::cout << "Normal Calculation " << sum.load() << std::endl; sum = 0; std::thread t1(calcSum, 0, 5000000); std::thread t2(calcSum, 5000001, 10000000); t1.join(); t2.join(); std::cout << "Threat Calculation " << sum.load() << std::endl; } |