How to openmp multithreaded programming on Linux system

  

OpenMP is a multi-processor multi-threaded programming language that can support multiple platforms, including Linux systems, then how to openmp multi-threaded programming under Linux? Let's get to know it.

key Syntax:

code is as follows:

#inlcude "omp.h"

#pragma omp parallel for

#pragma omp for reduction(+: variable)

#pragma omp critical//lock

{

}

#pragma omp parallel for private (x, y) //each thread independently copy x, y variables, do not interfere with each other, if not set to default is a shared variable

#pragma omp parallel for schedule(static/dynamic/guided, k) //The total workload is divided into n /k blocks, and then multi-threaded scheduling

#pragma omp parallel sections

{

#pragma omp section //to guarantee a few There is no variable dependency between functions under section

. . . . . . . . .

#pragma omp section

. . . . . . . . .

}

#pragma omp parallel

{

. . . . . . . ();

#pragma omp master/single //Ensure that only the main thread/a thread can access the following function, the difference is that the master does not have a barrier barrier, and the single thread that is completed first waits for the completion. Thread

{

}

. . . . . . .

}"/p" "p"#pragma omp barrier/nowait //Forcibly set the barrier/no need to wait, if the subsequent function does not depend on the previous multithread, you can use nowait

#pragma omp parallel for firstprivate (variable) /lastprivate (variable) //for each multi-threaded initial value /out of the multi-thread back to the main thread when the assignment is for the main thread to use

There is OpenMP API:

The code is as follows:

int omp_get_num_threads(); //Get the number of threads currently in use

int omp_get_num_threads(2/3/...) //Set the number of threads to use

nt omp_get_thread_num(void);//return the current thread number

int omp_get_num_procs(void);//return the number of available processing cores

Under ubuntu, you don't need to add the "omp.h" header file, just add -fopenmp when compiling.

For example: the emacs operation command is as follows

The code is as follows:

emacs omp.c "/p" "p"#include "stdio.h"

int main()

{

int rank, size;

#pragma omp parallel num_thread(3) private(rank) //num_threads is used to control the number of threads< Br>

//Or use omp_set_num_threads(3); "/p" "p" {

rank = omp_get_thread_num();

size = omp_get_num_threads();

printf(“using %d of %d now.\ ”, rank, size);

}

return 0;

}/p "p" ctrl+xs

alt+x compile

gcc -fopenmp -o omp omp.c

alt+shift+1 . /omp

The above is the introduction of OpenMP multi-threaded programming under Linux. This article mainly introduces OpenMP multi-threaded programming through an example. If you want to know more about it, you may wish to pay more attention to this. Stand it.

Copyright © Windows knowledge All Rights Reserved