Chapter: Multicore Application Programming For Windows, Linux, and Oracle Solaris - Synchronization and Data Sharing

Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail

Barriers

There are situations where a number of threads have to all complete their work before any of the threads can start on the next task.

Barriers

 

There are situations where a number of threads have to all complete their work before any of the threads can start on the next task. In these situations, it is useful to have a bar-rier where the threads will wait until all are present.

 

One common example of using a barrier arises when there is a dependence between different sections of code. For example, suppose a number of threads compute the values stored in a matrix. The variable total needs to be calculated using the values stored in the matrix. A barrier can be used to ensure that all the threads complete their computa-tion of the matrix before the variable total is calculated. Listing 4.10 shows a situation using a barrier to separate the calculation of a variable from its use.

 

Listing 4.10   Using a Barrier to Order Computation

Compute_values_held_in_matrix();

 

Barrier();

total = Calculate_value_from_matrix();

The variable total can be computed only when all threads have reached the barrier. This avoids the situation where one of the threads is still completing its computations while the other threads start using the results of the calculations. Notice that another barrier could well be needed after the computation of the value for total if that value is then used in further calculations. Listing 4.11 shows this use of multiple barriers.

 

Listing 4.11   Use of Multiple Barriers

Compute_values_held_in_matrix();

 

Barrier();

 

total = Calculate_value_from_matrix();

 

Barrier();

Perform_next_calculation( total );


Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail


Copyright © 2018-2020 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.