Last active
October 22, 2023 22:43
-
-
Save senderista/4d53a05e922458a946ffda619807ebf8 to your computer and use it in GitHub Desktop.
Simple example of atomic actions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "atomik.hpp" | |
void increment_balance(const char* account_name, int32 amount) | |
{ | |
atomik::do_atomically( | |
[]() { | |
atomik::var<Account> account_var = atomik::get_var_by_key(account_name); | |
auto account = account_var.get(); | |
account.balance += amount; | |
account_var.set(account); | |
} | |
); | |
} | |
void debit_balance(const char* account_name, int32 amount) | |
{ | |
try | |
{ | |
atomik::do_atomically( | |
[]() { | |
atomik::var<Account> account_var = atomik::get_var_by_key(account_name); | |
atomik::check( | |
account_var->balance >= amount, | |
atomik::timeout_sec(60)); | |
increment_balance(account_name, -amount); | |
} | |
); | |
} | |
catch (atomik::check_timeout&) | |
{ | |
std::cerr << "Insufficient funds!\n"; | |
} | |
} | |
void transfer_balance(const char* from_account_name, const char* to_account_name, int32 amount) | |
{ | |
atomik::do_atomically( | |
[]() { | |
increment_balance(from_account_name, -amount); | |
increment_balance(to_account_name, amount); | |
} | |
); | |
} | |
void print_balance(const char* account_name) | |
{ | |
atomik::do_atomically( | |
[]() { | |
atomik::var<Account> account_var = atomik::get_var_by_key(account_name); | |
atomik::on_commit([=]() { | |
std::cout << std::format("Balance for {}: {}\n", account_name, account_var->balance); | |
}); | |
}, | |
atomik::action_type::read_only | |
); | |
} | |
atomik::do_atomically( | |
[]() { | |
print_balance("Accounts.Alice"); | |
print_balance("Accounts.Bob"); | |
} | |
); | |
transfer_balance("Accounts.Alice", "Accounts.Bob", 10); | |
atomik::do_atomically( | |
[]() { | |
print_balance("Accounts.Alice"); | |
print_balance("Accounts.Bob"); | |
} | |
); | |
debit_balance("Accounts.Alice", 100); | |
print_balance("Accounts.Alice"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment