Critical section of OpenMP thread synchronization

Source: Internet
Author: User
Tags execution printf thread

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 .

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.