/* example2 note: iostream is not thread-safe. cout calls must be executed in critical areas or by only one thread. What it does: forks a number of threads; each thread prints its thread-id. They all wait at a barrier. then the master prints the number of threads. */ #include #include int main() { int th_id, nthreads; #pragma omp parallel private(th_id) shared(nthreads) /* th_id and nthreads are declared above. th_id is private to each thread, and nthreads is shared */ { th_id = omp_get_thread_num(); #pragma omp critical //this block is specified as critical, meaning its executed by one //thread at a time { std::cout << "Hello World from thread " << th_id << '\n'; } #pragma omp barrier //each thread waits until all other threads have reached this point #pragma omp master //this block is specified as master, meaning its executed only by //the master thread { nthreads = omp_get_num_threads(); std::cout << "There are " << nthreads << " threads" << '\n'; } } return 0; }