Title: Class 20: Mutual Exclusion
Date: 2014-04-10
Category: Classes
Tags: operating systems, kernel, kernel programming, synchronization, Dijkstra, Lamport, mutual exclusion
Author: David Evans

   <div class="todo"> 
   <center>
**[PS4 Assessment](https://docs.google.com/forms/d/1_MONt8V99KtucMRswC2L6yUtXlKYK9CY3wB9Ubf_MFY/viewform)** due after your demo (by tomorrow at the latest)  
**[Project Idea](https://docs.google.com/forms/d/1Sxg5aJuhEWPVpVzUzEBrTsChRsn2wtJogsd7ycSjcTk/viewform)** due by **11:59pm Thursday (tonight)**.
   </center>
   </div>

<center>
<iframe src="http://www.slideshare.net/slideshow/embed_code/33379935" width="476" height="400" frameborder="0" marginwidth="0" marginheight="0" scrolling="no"></iframe>
</center>

# Projects/Hackathon Update

<center>
<iframe width="560" height="315" src="//www.youtube.com/embed/OPTkjLXbmf0?list=PLvpsxlEF9cP07YyhdvphZxLSjluZ9h8OY" frameborder="2" allowfullscreen></iframe>
</center>

# Mutual Exclusion

<center>
<iframe width="560" height="315" src="//www.youtube.com/embed/kzQik4bQeh0?list=PLvpsxlEF9cP07YyhdvphZxLSjluZ9h8OY" frameborder="2" allowfullscreen></iframe>
</center>

**Requirements:**

1. Only one thread may be in the critical section at any time.
2. Each must eventually be able to enter its critical section.
3. Must be symmetrical (all run same program, cannot introduce static priority).
4. Cannot make any assumptions about speed of threads.

What's "wrong" with this solution?
```python
loop {
    if turn == i:     
         critical_section;
         turn = i + 1;
}
```

What's "wrong" with this solution?
```python
loop {
    if not lock: 
         lock = true;
         critical_section;
         lock = false;
}
```

## Test and Set

<center>
<iframe width="560" height="315" src="//www.youtube.com/embed/FkRZpg7jTQU?list=PLvpsxlEF9cP07YyhdvphZxLSjluZ9h8OY" frameborder="2" allowfullscreen></iframe>
</center>

Atomic instruction that:
- returns current value of _v_
- sets value of _v_ to true

How can you implement mutual exclusion using _test-and-set_?
<div class="gap">

</div>

## ARM's Exclusion Instructions

**LDREX** _dest_ _location_  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;_dest_ = _location_  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Sets monitor on _location_ in Exclusive state

**STREX** _success_ _value_ _location_  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Conditionally store <value> into exclusive <location>.  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;If permitted, <success> = 1 and <location> = <value>.  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;If not, <success> = 0 and <location> value unchanged.  

Context switch clears monitor (Open) state.

[_ARM Synchronization Primitives_](http://infocenter.arm.com/help/topic/com.arm.doc.dht0008a/DHT0008A_arm_synchronization_primitives.pdf)

```
lock_mutex(lock):
try_again:    
        LDREX R2, [lock]
        if R2 goto try_again
        STREX R2, 1, [lock]
        if not R2 goto try_again

unlock_mutex(lock):
        STR [lock], 0
```

Why don't we need to use **STREX** in unlock?
<div class="gap">

</div>

How should this be different if we care about energy?
<div class="gap">

</div>

# Dijkstra's Solution

<center>
<iframe width="560" height="315" src="//www.youtube.com/embed/nNW9KhYnF6c?list=PLvpsxlEF9cP07YyhdvphZxLSjluZ9h8OY" frameborder="2" allowfullscreen></iframe>
</center>

```python
   loop {         
         b[i] := false
L1:	 if k != i 
               c[i] := true
    	             if b[k]:
        	              k := i
                  goto L1
         else:
               c[i] := false
               for j in [1, ..., N]:
                    if j != i and not c[j]:
                         goto L1  
               critical section;   
               c[i] := true
               b[i] := true    
    }
```

Why is this guaranteed to provide mutual exclusion?
<div class="gap">

</div>

How do we know threads will make progress?
<div class="gap">

</div>

[Dijkstra's Cry for Generalization](http://www.dijkstrascry.com/)

<div id="disqus_thread"></div>

<script type="text/javascript">
        /* * * CONFIGURATION VARIABLES: EDIT BEFORE PASTING INTO YOUR WEBPAGE * * */
        var disqus_shortname = 'rust-class'; // required: replace example with your forum shortname
	var disqus_url = 'http://www.rust-class.org/class-20-mutual-exclusion.html';

        /* * * DON'T EDIT BELOW THIS LINE * * */
        (function() {
            var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
            dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
            (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
        })();
</script>
<noscript>Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
<a href="http://disqus.com" class="dsq-brlink">comments powered by <span class="logo-disqus">Disqus</span></a>
