Learning OpenMP (7) together -- critical section of Thread Synchronization

Source: Internet
Author: User

I. Introduction

The previous section describes the usage of the atomic mutex lock mechanism in OpenMP. This section describes the usage of the Critical Zone mutex lock mechanism. The critical section here is similar to the criticalsection in windows.

 

Ii. critical section declaration method

# Pragma OMP critical [(name)] // [] indicates the name is optional

{

// Parallel program block. Only one thread can access this parallel program block.

}

 

For example:

# Prgama OMP critical ()

A = B + C;

 

Iii. Example

# Include <iostream> <br/> # include <OMP. h> // header file to be included in OpenMP programming </P> <p> int main () <br/>{< br/> int sum = 0; </P> <p> STD: cout <"before:" <sum <STD: Endl; </P> <p> # pragma OMP parallel for <br/> for (INT I = 0; I <100; ++ I) <br/>{< br/> # pragma OMP critical (a) <br/>{< br/> sum = sum + I; <br/> sum = sum + I * 2; <br/>}</P> <p> STD: cout <"after: "<sum <STD: Endl; <br/> return 0; <br/>}

 

Iv. Summary

The usage of the critical section critical is introduced. The difference between critical and atomic is that atomic is only applicable to the two types of operations specified in the previous section, and atomic is only protected by a single code. Critical can protect a parallel program block. The next section describes the mutex functions provided by OpenMP.

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.