6 # Classical increment examples
8 * Threads are incrementing a counter
9 * Thread A reads the counter from memory
10 * Thread A is interrupted
11 * Thread B reads the counter from memory
12 * Thread B increments the counter
13 * Thread B saves the counter to memory
14 * Thread A executes and now has the wrong value in its registers
18 In the last example, the section of code that increments the *global*
19 counter is a critical section.
23 The problem in here is sharing data with multiple threads. When sharing,
24 we need to serialize the access, that is, only one thread may execute
25 the critical section at a time.
29 * The Philosophers' Dinner
31 * Consumer and Producer
33 # Linux historical race handling
37 * semaphores/old mutexes
42 # Semaphores and mutexes
46 * include linux/semaphore.h
50 * sema\\_init(sem, val)
52 * init\\_MUTEX\\_LOCKED(sem)
53 * DECLARE\\_MUTEX(varname)
54 * down\\_interruptible(sem)
58 * Ingo Molnar's design
59 * Documented at Documentation/mutex-design.txt
61 # How to use the new mutex
65 * DEFINE\\_MUTEX(varname)
69 # When you should or should not use them
71 * They both sleep, so take care: no atomic contexts
72 * When the critical section may sleep
76 * include linux/spinlock.h
77 * Documentation/spinlocks.txt
89 * spin\\_lock\\_irqsave
90 * spin\\_unlock\\_irqrestore
92 # When you should and should not use them
94 * They can be used in atomic contexts
95 * They lock the processor when "waiting", so use for fast critical
97 * They create an atomic context themselves, so *do not* sleep while
106 * atomic\\_add\\_return(i, \\&v)
107 * atomic\\_add(i, \\&v)
108 * atomic\\_inc(i, \\&v)
111 * atomic\\_dec\\_and\\_test
115 May be used for locking, but spinlocks are better nowadays.
120 * DEFINE\\_PER\\_CPU(type, name)
121 * get\\_cpu\\_var(name)
122 * put\\_cpu\\_var(name)
123 * per\\_cpu(name, cpu)
124 * alloc\\_percpu(type)
127 * per\\_cpu\\_ptr(var, cpu)
134 * rcu\\_read\\_unlock
135 * rcu\\_assign\\_pointer
143 * list\\_add\\_tail\\_rcu
145 * list\\_for\\_each\\_entry\\_rcu