OpenMP: Work sharing and controlling thread data#

1. Work sharing constructs#

  • OpenMP utilizes work sharing constructs to facilitate dividing parallelizable work among a number of threads.

  • The work sharing constructs are:

    • for: divide loop iterations among threads.

    • sections: divide sections of codes among themselves.

    • single: the section is executed by a single thread.

2. Work sharing constructs: sections#

Definition
  • Used when parallelize predetermined number of independent work units.

  • Within a primary sections construct, there can be multiple section construct.

  • A section can be executed by any available thread in the current team, including having multiple sections done by the same thread.

Hands-on
  • In the EXPLORER window, double-click on openmp and select New Dir to create a new directory in openmp called sections.

  • Inside sections, create a file named hello_sections.c with the following contents:

compile and run hello_sections.c
Challenge

Given the following functions: y=x4 + 15x3 + 10x2 + 2x
develop an OpenMP program called poly_openmp.c with sections/section directives. Each section should handle the calculations for one term of the polynomial.

Solution

3. Work sharing construct: single#

Definition
  • Limits the execution of a block to a single thread.

  • All other threads will skip the execution of this block but wait until the block is finished before moving on.

  • To enable proceed without waiting, a nowait clause can be added.

Hands on: single
  • Inside sections, create the following files:

hello_sections_nosingle.c:

hello_sections_single.c:

hello_sections_single_nowait.c:

Compile and run the above files:

compile and run singles

4. Shared and private data#

Definition
  • Data declared outside of a parallel region will be shared among all threads.

  • Data declared inside of a parallel region will be private to individual thread.

Hands-on: potential problems with shared data
  • Inside sections, create a file named counter_openmp.c with the following contents:

../_images/work_03.png