by David J. Malan <malan@post.harvard.edu>
Printer-Friendly Version of Tutorial

« Previous | Table of Contents | Next »

Threads

In programming, a thread is like a mini-program within a program that can execute at the same time as other threads. A program with multiple threads, then, can do multiple things at once. In Scratch, any block whose label begins with "when" essentially demarks the start of a thread; think of what Scratch calls a "script" as a thread. (Technically, scripts run in threads, but never mind that.)

One such block is:



As the above block's label suggests, this thread begins to execute when the user click's Scratch's green flag. A program with two such blocks thus has two "threads of execution," both of which start simultaneously when the user clicks Scratch's green flag.

It's often helpful to use separate threads for conceptually distinct tasks. For instance, you might want to keep track of whether the user ever presses some key during a program's execution in order to, say, toggle sound on and off:



Notice how, in the above, the left-hand thread handles meowing, if appropriate, whereas the right-hand thread constantly checks and remembers whether the user has muted or unmuted sound by pressing the space bar.

Related to threads are events, to which we turn our attention next.

« Previous | Table of Contents | Next »