KomodoPlatform / komodo-defi-framework

This is the official Komodo DeFi Framework repository
https://komodoplatform.com/en/docs/komodo-defi-framework/
103 stars 94 forks source link

`compare_exchange` and spinlock implementation #1441

Open onur-ozkan opened 2 years ago

onur-ozkan commented 2 years ago

compare_exchange is quite heavy operation which should never spin in a loop over and over like here here on multi-threaded systems. Since it tries to have exclusive access to the desired memory location, the running threads have to try getting that access over and over. Which is obviously not an efficent way to do so.

There are many things can be done on this implementation to make it more efficent. Like instead of trying compare_exchange it can be replaced with the compare_exchange_weak function (this performs little bit better on some platforms and there is no problem with using it if it's running under the loop). But still, it should not be executed over and over since we don't want to make our threads wasting too much power for exclusive access.

An efficent way to use compare_exchange_weak(dummy code):

while x.compare_exchange_weak(true(current value), false(new value), ...).is_err() {
    while x.load() == false {} // Checking if the current value isn't true, so no need to execute compare_exchange_weak over and over
}

ToDos:

cc @artemii235 @sergeyboyko0791 @shamardy

onur-ozkan commented 2 years ago

PS: For x86 family(and probably some arm families specially modern ones if I am not mistaken) compare_exchange has single atomic instruction which reduces the overhead. But still heavier than just loading the value.