Porting InterlockedExchange, Only Using GCC Properties

The Windows API offers InterlockedExchange , which sets the value in memory atomically. Using only the properties of GCC, Id like to create the equivalent of this function. Would it be enough to set the value and then call the memory barrier (see code below)?

 template <typename T> T InterlockedExchange(volatile T& _data, T _value) { const T oldValue = _data; _data = _value; __sync_synchronize(); return oldValue; } 

Thanks.

EDIT . The proposed fragment is NOT the correct solution to the problem, since it is clearly not atomic (but, for the best, I had to try at least).

+4
source share
2 answers

Use __sync_val_compare_and_swap __sync_lock_test_and_set , not __sync_synchronize .

This has the same function as InterlockedExchange.

Something like this (untested code!):

 template<typename T> T InterlockedExchange(T& data, T& new_val) { return __sync_lock_test_and_set(&data, new_val); } 

EDIT:
Oi, I read incorrectly, you wanted InterlockedExchange, not InterlockedCompareExchange ... so this is __sync_lock_test_and_set (the name is misleading Intel number, but this is exactly what you want).
See here at the bottom of the page.

+9
source

Your suggested example is not equivalent because it is not atomic. Two racing threads performing your function can retrieve the same old value, one of the new values ​​being β€œlost”.

0
source

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


All Articles