Skip to content

Intro to Multithreading

Samuel H edited this page Jul 22, 2021 · 1 revision

In the previous tutorial have seen how to use multiple notes. In this tutorial we will see how to make use of the threading capabilities of TSAL.

Linux/Mac/Cygwin users: Start off by creating a folder and name it "Tutorial3". Create a file inside of Tutorial3 and name it "thread.cpp". Then, navigate to the cloned TSAL folder and into the genericMakefile folder. Copy the Makefile into Tutorial3 and change the "TARGET" line so that "program" is now "thread". Follow the steps in the Building Programs page on how to compile and run the program (this is a single-file program).

Since we are going to parallelize our program using OpenMP, we need to include omp.h:

#include "tsal.hpp"
#include <omp.h>

using namespace tsal;

We will use the code we wrote in the previous tutorial

#include "tsal.hpp"
#include <omp.h>
using namespace tsal;

int main() {
  Mixer mixer;
  ThreadSynth synth(&mixer);
  mixer.add(synth);
  synth.setEnvelopeActive(false);

  const int SIZE = 6;

  for (int i = 0; i < SIZE; i++) {
    MidiNote note = Util::scaleToNote(i, std::make_pair(0, SIZE), std::make_pair(C4, C7));
    synth.play(note, Timing::SECOND, 1);
  }

}

After compiling and running the above code, you should hear 6 notes playing, since we made the SIZE equal to 6. Now let's bring in the multithreading:

#include "tsal.hpp"
#include <omp.h>
using namespace tsal;

int main() {
  Mixer mixer;
  ThreadSynth synth(&mixer);
  mixer.add(synth);
  synth.setEnvelopeActive(false);

  const int SIZE = 6;

  // Set the number of threads
  omp_set_num_threads(2);

  // fork additional threads to work inside the pragma block
  #pragma omp parallel
  {
    //distribute loop iterations within the set number of threads
    #pragma omp for
    for (int i = 0; i < SIZE; i++) {
      MidiNote note = Util::scaleToNote(i, std::make_pair(0, SIZE), std::make_pair(C4, C7));
      synth.play(note, Timing::SECOND, 1);
    }

  }

}

The above code is doing the following:

  • Setting the number of threads
  • Creating a pragma parallel block
  • Distributing the threads for each for loop iterations

Compile and run the above code. You should hear only 3 notes playing. This is because we have a SIZE of 6 but we are using two threads to parallelize it. This resulted in only 3 notes being played.

That concludes this tutorial. In the next tutorial, we will dig deeper into Multithreading.

Clone this wiki locally