Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Synchronizing access to variable

I need to provide synchronization to some members of a structure.
If the structure is something like this

struct SharedStruct {
    int Value1;
    int Value2;
}

and I have a global variable

SharedStruct obj;  

I want that the write from a processor

 obj.Value1 = 5; // Processor B

to be immediately visible to the other processors, so that when I test the value

 if(obj.Value1 == 5) { DoSmth(); } // Processor A
 else DoSmthElse();   

to get the new value, not some old value from the cache.
First I though that if I use volatile when writing/reading the values, it is enough. But I read that volatile can't solve this kind o issues.
The members are guaranteed to be properly aligned on 2/4/8 byte boundaries, and writes should be atomic in this case, but I'm not sure how the cache could interfere with this.
Using memory barriers (mfence, sfence, etc.) would be enough ? Or some interlocked operations are required ?
Or maybe something like

lock mov addr, REGISTER  

?
The easiest would obviously be some locking mechanism, but speed is critical and can't afford locks :(

Edit
Maybe I should clarify a bit. The value is set only once (behaves like a flag). All the other threads need just to read it. That's why I think that it may be a way to force the read of this new value without using locks.

Thanks in advance!

like image 262
Gratian Lup Avatar asked Feb 20 '26 23:02

Gratian Lup


1 Answers

There Ain't No Such Thing As A Free Lunch. If your data is being accessed from multiple threads, and it is necessary that updates are immediately visible by those other threads, then you have to protect the shared struct by a mutex, or a readers/writers lock, or some similar mechanism.

Performance is a valid concern when synchronizing code, but it is trumped by correctness. Generally speaking, aim for correctness first and then profile your code. Worrying about performance when you haven't yet nailed down correctness is premature optimization.

like image 104
peterb Avatar answered Feb 23 '26 12:02

peterb



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!