How to? Synchronizing two threads

In the EV3 programming environment, it is possible to start multiple threads. For example, you want two motors to run simultaneously and when both motors are finished, you want to play a sound. But there is no default mechanism in the programming environment to continue with the main thread when the second has also finished. In  the example below, the “Ready” sound is played too early if motor A finishes before motor B is finished.

So, how do you solve this problem? If you use a logic variable (called SyncVar in  the example below), you can synchronize the two threads. Before you start the threads, the variable is set to “false”. And you wait until the variable is “true” before you play the ‘Ready’ sound. Two things can happen:

  1. Motor A finishes before Motor B. The wait loop is entered and it doesn’t exit until the motor in thread B finishes as well.
  2. Motor B finishes before Motor A. The wait loop is entered but also immediately exited (the variable SyncVar is already set to ‘true’).

With this simple solution, you can synchronize two threads. But watch out: if this part of the program is again part of a multi threaded program, you should be aware that the value of the SyncVar cannot be guaranteed.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s