Structure Exchange Lock

I want to use InterlockedExchange from WinAPI to use thread synchronization without blocking.
At the moment I have a class like this.

struct DataExchange { volatile LONG m_value; void SetValue(LONG newVal) { InterlockedExchange(&m_value, newVal); } LONG GetValue() { LONG workVal=0; InterlockedExchange(&workVal, m_value); return workVal; } }; 

One thread can set a new value, and another thread can read this value.
Now I want to change the LONG value as a struct . Is there a way in WinAPI how can I copy a struct lock?

+6
source share
4 answers

No, if you cannot put your structure in 32 bits, then you can continue to use InterlockedExchange.

+3
source

Only if the structure has exactly 32 bits.

An alternative is to use InterlockedExchange on a pointer to a structure. The structure must be unchanged (or never change it). To update the structure, create a new one and then exchange the pointer. You must be careful in destroying the structure to make sure that it is executed only once, and only if no one is using it.

+1
source

The best you can do is use the InitializeCriticalSectionAndSpinCount function, which will not wait for a lock if you can quickly own the property enough.

+1
source

You can get an atomic operation with a 64-bit value using InterlockedExchange64 on 64-bit platforms and in Windows Vista / 7. This would be enough to match the two 32-bit int values ​​in the structure.

Since the function is implemented using the built-in integrator, it basically invokes a platform-specific assembly, such as x86 CMPXCHG . Since this command only works with the maximum (on 64-bit platforms) in a 64-bit register source operand, a 64-bit register or memory assignment operand, and in the RAX register, there is only a certain value that you can perform an atomic operation using separate instructions assembly without including any type of lock or semaphore to create a critical partition.

+1
source

Source: https://habr.com/ru/post/888899/


All Articles