OpenMP is a library that supports shared-memory multithreading on C/C++/Fortran.1 It’s contained in the omp.h header file.

The code below enables a parallelised for loop, assuming the compiler supports it.

#pragma omp parallel for
for (int i = 0; i < 100; i++)
	// code

Oftentimes OpenMP works best with simple loops.

There’s inversely diminishing returns with larger loops. For smaller loops it’ll take more time to set up the threads than to actually just run the loop sequentially. There’s always some overhead in setting up the threads (the effect is just more pronounced for smaller loop sizes).

#pragma omp critical ensures only one thread at a time can execute a given block of code.

Footnotes

  1. ”The poor man’s multithreading.” - Alex Singer