Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Synchronizing caches in a multithreaded program on multi-core system

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.

like image 925
adisticated Avatar asked Mar 09 '26 13:03

adisticated


1 Answers

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.

like image 137
Johnny Avatar answered Mar 11 '26 11:03

Johnny



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!