Learning OpenMP (6) together -- Atomic of Thread Synchronization

Source: Internet
Author: User

I. Introduction

In OpenMP, the thread synchronization mechanism includes the mutex lock synchronization mechanism and event synchronization mechanism. This section describes the atomic method in the mutex lock synchronization mechanism.

 

Ii. mutex lock synchronization Concept

The concept of mutex synchronization is similar to the criticalsection in windows, the mutex in Windows and Linux, and the semtake semgive in VxWorks (the semaphore is full during initialization ), that is, to protect a piece of code operations, to ensure that only one thread can execute this section of code at the same time.

 

Iii. Atomic (atomic) operation syntax

# Pragma OPM atomic

X <+ or * or-or * Or/or & or | or <or> = expr

(For example, x <= 1; or x * = 2 ;)

Or

# Pragma OPM atomic

X ++ // or X --, -- X, ++ x

It can be seen that the atomic operation only applies to two situations:

1. Auto increment/Subtraction

2. x <operations listed above> = expr

 

Iv. 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 <20000; ++ I) <br/>{< br/> # pragma OMP atomic <br/> sum ++; <br/>}</P> <p> STD :: cout <"after:" <sum <STD: Endl; <br/> return 0; <br/>}

20000 output.

If the # pragma OMP atomic declaration is removed, the output value is uncertain.

 

Section 5

This section describes the usage of atomic and the usage of critical section.

 

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.