Snap! supports parallelism! Let's explore one of the fun/challenges of concurrent programming: nondeterminism. In this context, this means we cannot pre-determine what the results will be; determinism means we could predict what the outputs would be.
In the last Snap! exercise, it was a little artificial; the
sprites were in lock step. Let's take a look at a similar project,
Determinism
. Here,
four 60x60 sprites do the same thing (color the screen by stamping
themselves through the Fill Screen
command shown below),
and once they finish, they add their name to the end of the finish
variable. Run it a couple of times. Boring, right? That was because
Snap! is still in lock step.
Make a very small change to Fill Screen - have each sprite wait a
random value between 1 and 1/10 seconds before stamping. (this involves
the introduction of a very simple command right before the "stamp" call
in Fill Screen
: "wait (1 / (pick random [1] to [10]))
secs"). Run it a few times; now what happens? (Answer: Four "threads"
take off, and the slowest (i.e., last) color at each time step is that
one who colors that 60x60 square). Save this project as a Snap! file
called NonDeterminism.xml
.