Synchronous mutexes are definitely used in multi-core/multithreaded programming. In addition to the mutex variable, it is the critical section.
A critical section is a section of code that is surrounded by {...}, which is used to allow only one thread to execute at one time.
The critical Zone declaration method in OpenMP is as follows:
#pragma omp critical [(name)]//[] indicates an optional name
{
Code that requires only one thread to access at the same time
}
As in the following code:
#include <stdio.h>
#include <omp.h>
int main ()
{
int sum = 0;
#pragma omp parallel
printf ("Hello World!!! \ n ");
#pragma omp parallel for
(int i = 0; i < 10000; ++i)
{
#pragma omp critical
{
sum = sum + i% 7;
}
}
printf ("Sum:%d\n", sum);
return 0;
}
Execution results:
As you can see, the machine has 8 cores, and 8 threads are started. if the 13th line in the code is commented out, the sum in the execution result is basically indeterminate .