This article mainly introduces the openmp multi-thread programming example in linux. For more information, see
Key syntax:
Copy codeThe code is as follows:
# Inlcude
# Pragma omp parallel
# Pragma omp for callback ction (+: variable)
# Pragma omp critical // lock
{
}
# Pragma omp parallel for private (x, y) // Each thread copies the x and y variables independently and does not interfere with each other. If no shared variable is set
# Pragma omp parallel for schedule (static/dynamic/guided, k) // The total workload is divided into n/k blocks, and then multi-thread scheduling
# Pragma omp parallel sections
{
# Pragma omp section // ensure that there is no variable dependency between functions under several sections
.........
# Pragma omp section
.........
}
# Pragma omp parallel
{
.......();
# Pragma omp master/single // ensure that only the main thread/a thread can access the following functions. The difference is that the master has no barriers to barriers, single, the first thread is waiting for the thread to be completed
{
}
.......
}
# Pragma omp barrier/nowait // forcibly sets the Mountain fault/does not need to wait. if subsequent functions do not depend on the preceding multithreading, you can use nowait
# Pragma omp parallel for firstprivate (variable)/lastprivate (variable) // assign an initial value to each multithreading/assign a value when multiple threads return to the main thread for use by the main thread
There is also the OpenMP API:
Copy codeThe code is as follows:
Int omp_get_num_threads (); // gets the number of threads currently in use
Int omp_get_num_threads (2/3/...) // you can specify the number of threads to be used.
Nt omp_get_thread_num (void); // returns the current thread number.
Int omp_get_num_procs (void); // returns the number of available processing cores.
In ubuntu, you do not need to add Header file, you only need to add-fopenmp during compilation.
For example, the emacs operation command is as follows:
Copy codeThe code is as follows:
Emacs omp. c
# Include
Int main ()
{
Int rank, size;
# Pragma omp parallel num_thread (3) private (rank) // num_threads is used to control the number of threads
// Or use omp_set_num_threads (3 );
{
Rank = omp_get_thread_num ();
Size = omp_get_num_threads ();
Printf ("using % d of % d now. \ n", rank, size );
}
Return 0;
}
Ctrl + x s
Alt + x compile
Gcc-fopenmp-o omp. c
Alt + shift + 1./omp