Created
November 7, 2025 23:49
-
-
Save shivamka1/f23c86e860a4856ced1033934fd23a50 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| locks = Map<productId, LockObject>() | |
| function get_lock(productId): | |
| if productId not in locks: | |
| locks[productId] = new LockObject() | |
| return locks[productId] | |
| function purchase(productId): | |
| lock = get_lock(productId) | |
| synchronize(lock): # one thread per product at a time | |
| stock = query("SELECT stock FROM products WHERE id = ?", productId) | |
| if stock <= 0: | |
| return "Out of stock" | |
| exec("UPDATE products SET stock = stock - 1 WHERE id = ?", productId) | |
| return "OK" |
Comments are disabled for this gist.