How to ensure that the caches on different cores/processors are in sync with each other at any instant. For example:
Thread 1:
while(1) {
a++;
}
Thread 2:
While(1) {
if(a%2 == 0) {
// do something
}
}
In thread 2, when a is tried to be accessed, a would not reflect the latest value. Would this implementation using locks be a correct solution? :
Thread 1:
while(1) {
a++;
}
Thread 2:
while(1){
lock();
unlock();
if(a%2 == 0) {
// do something.
}
}
Desired behavior is that we want the two threads to be as much synchronized as possible.
If you want to synchronize a++; and if(a % 2 == 0) { /* do something */ } you should try this:
std::mutex mtx;
// Thread 1:
while(1) {
mtx.lock();
a++;
mtx.unlock();
}
// Thread 2:
while(1){
mtx.lock();
if(a%2 == 0) {
mtx.unlock();
// do something.
}
mtx.unlock();
}
Locking a specific mutex every time before you want to use a specific resource, and unlocking it when you are done, ensure you that the operations on that resource are synchronized.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With