Simulator
This lesson explains how to interact with the simulator for exercise on threads.
We'll cover the following...
Welcome to the simulator for the basics of threads. The idea is to gain familiarity with threads by
seeing how they interleave; the simulator, x86.py
, will help you in
gaining this understanding.
The simulator mimics the execution of short assembly sequences by multiple threads. Note that the OS code that would run (for example, to perform a context switch) is not shown; thus, all you see is the interleaving of the user code.
The assembly code that is run is based on x86, but somewhat simplified.
In this instruction set, there are four general-purpose registers
(%ax
, %bx
, %cx
, %dx
), a program counter (PC
), and a small set of instructions
which will be enough for our purposes.
Here is an example code snippet that we will be able to run:
.main
mov 2000, %ax # get the value at the address
add $1, %ax # increment it
mov %ax, 2000 # store it back
halt
The code is easy to understand. The first instruction, an x86 mov
, simply
loads a value from the address specified by 2000 into the register %ax
.
Addresses, in this subset of x86, can take some of the following forms:
-
2000 -> the number (2000) is the address
-
(
%cx
) -> contents of register (in parentheses) forms the address -
1000(
%dx
) -> the number (1000) + contents of the register form the address -
10(
%ax
,%bx
) -> the number (10) + reg1 + reg2 forms the address
To store a value, the same mov
instruction is used, but this time with the
arguments reversed, e.g.:
mov %ax, 2000
The add
instruction, from the sequence above, should be clear: it adds an
immediate value (specified by $1) to the register specified in the second
argument (i.e., %ax
= %ax
+ 1).
Thus, we now can understand the code sequence above: it loads the value at address 2000, adds 1 to it, and then stores the value back into address 2000.
The fake-ish halt
instruction just stops running this thread.
Let’s run the simulator and see how this all works! Assume the above code
sequence is in the file simple-race.s
.
prompt> ./x86.py -p simple-race.s -t 1
Thread 0
1000 mov 2000, %ax
1001 add $1,
...