Concurrency — what is it?

One of Scratch’s most notable and useful features is its ability to execute scripts in parallel. This means the computer doesn’t need to wait for one script to finish running before executing the next script.

This is known as concurrency. The Scratch programmer doesn’t have to worry about the order their scripts are being executed in, they can just assume that they will all run at the same time.

Here’s an example of a program displaying such concurrency:

2-4-1.png

When this program is run, both scripts are executed simultaneously. This causes the sprite they are attached to to switch between saying “On” and “Off” every half a second.

Most text-based programming languages do not allow the programmer to execute multiple parts of their program in parallel with such ease. For this reason, it is necessary for students that are new to such languages to learn to rethink how such problems can be tackled.

A student who is starting to learn Python might try and create the above Scratch script in the following way:

from time import sleep

while True:
    sleep(0.5)
    print("On")
    sleep(0.5)

while True:
    sleep(1)
    print("Off")

However, running this script will cause On to be printed until the program is forcibly quit. Off never gets printed.

Hence, to replicate the Scratch script so that it works in Python, the code needs to be condensed into a single loop.

from time import sleep

while True:
    sleep(0.5)
    print("On")
    sleep(0.5)
    print("Off")

This can sometimes be a struggle for students to understand, so it is an important concept to tackle fairly early on when they transition to writing programs in in a text-based language.

Share this article:

This article is from the free online course:

Scratch to Python: Moving from Block- to Text-based Programming

Raspberry Pi Foundation