In a single-core multi-threaded program, you often need to synchronize multiple threads to complete the task. In this process, some threads will be suspended. In OpenMP, barrier is required to synchronize various threads.
Test code:
Void testBarrier ()
{
Omp_set_num_threads (4 );
# Pragma omp parallel
{
Printf ("test OpenMP 1/n ");
# Pragma omp barrier
Printf ("test OpenMP 2/n ");
}
}
The running result is:
Test OpenMP 1
Test OpenMP 1
Test OpenMP 1
Test OpenMP 1
Test OpenMP 2
Test OpenMP 2
Test OpenMP 2
Test OpenMP 2
If barrier is not used,
Void testBarrier ()
{
Omp_set_num_threads (4 );
# Pragma omp parallel
{
Printf ("test OpenMP 1/n ");
// # Pragma omp barrier
Printf ("test OpenMP 2/n ");
}
}
The running result is:
Test OpenMP 1
Test OpenMP 2
Test OpenMP 1
Test OpenMP 2
Test OpenMP 1
Test OpenMP 2
Test OpenMP 1
Test OpenMP 2
Therefore, when barrier is used, after executing the latest parrallel region code before the barrier is located with only all threads,
The code after the barrier is executed.