Practical guide to

Atomic Operations

Created by Aidas Klimas

Agenda

  1. What is an atomic operation
  2. File system atomic operations
  3. Cache atomic operations
  4. Database atomic operations
  5. Atomic operations vs Locks
  6. Workshop!

What is an atomic operation?

Any indivisible operation operating systems can do atomically, making them useful as building blocks for thread-safe and multi-process-safe programs without mutexes or read/write locks

File system atomic operations


							mv file-path file-path-2 # move file once

							mkdir folder-path # create file once
							
Terminal connection session 1

								mv file-path file-path-2 # FAIL
							
Terminal connection session 2

								mv file-path file-path-2 # SUCCESS
							

Full list https://rcrowley.org/2010/01/06/things-unix-can-do-atomically.html

Database atomic operations


								CREATE TABLE dogs (
									id INT PRIMARY KEY, name varchar(255)
								);

								INSERT INTO dogs (id, name) VALUES
									(1, 'Gile'), (2, 'Pukis'); -- 2 rows affected
								INSERT INTO dogs (id, name) VALUES
									(1, 'Gile'), (2, 'Pukis'); -- 0 rows affected

								update dogs set name = 'labas' where id = 1; -- 1 rows affected
								update dogs set name = 'labas' where id = 1; -- 0 rows affected

								delete from dogs where id = 1; -- 1 rows affected
								delete from dogs where id = 1; -- 0 rows affected
							

Cache atomic operations


								Cache::add('cache-key', 'value'); // true
								Cache::add('cache-key', 'value 2'); // false

								Cache::put('cache-key', 'value') // always true, not very useful

								Cache::forget('cache-key');
							

Atomic increment


								Cache::increment('cache-key');
							
VS NON ATOMIC

								$value = Cache::get('cache-key');
								Cache::put('cache-key', $value + 1)
							

Atomic operations vs Locks

  • Atomic operations are fast. Can be made with a single network request
  • No deadlocks
  • Easy to use

Workshop Incoming!

First, prepare!

Go to
https://gitlab.com/ekomlita/workshop/atomic-operations-workshop
clone and follow readme

Thank You!

Questions?

Get slides from klimas.lt/slides