Jih-Wei Liang
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    # 3 Introduction into OpenMP 5.0 ###### tags: `SS2021-IN2147-PP` ## OpenMP and its Execution Model ### Terminology HW Threads * A single system has many hardware threads * A **`system/node`** can have multiple **`physical processors`** (aka. **`sockets`**) * Independent chips with their own interconnect between them * Each **`socket`** can have multiple **`cores`** * Replicated processors on a single die with on-die interconnect * Each **`core`** can run multiple **`hardware threads`** * `Simultaneous Multithreading / Hyperthreading` * Separate PC and Stack Pointer, but shared resources ### OpenMP = Open Multi-Processing * Standard for writing parallel programs, mainly **`on-node`** * `Shared memory parallelism` * **Portability** * 3 primary API components: * Compiler Directives (for C/C++ and Fortran) * Runtime Library Routines * Environment Variables * **OpenMP is not ...** * intended for distributed memory systems * necessarily implemented identically by all vendors * guaranteed to automatically make the most efficient use of shared memory * required to check for data dependencies, race conditions, deadlocks, etc. * designed to handle parallel I/O ### Fork/Join Execution Model ![](https://i.imgur.com/xbaO98o.png) ### Nested Parallelism ![](https://i.imgur.com/Xh8xqMf.png) ### OpenMP System Stack ![](https://i.imgur.com/ycnIQ3I.png) ## OpenMP Syntax ```c // Most of the constructs in OpenMP are compiler directives #pragma omp construct [clause [clause]...] // Directives can have continuation lines #pragma omp parallel private(i) \ private(j) ``` ### Parallel Regions ```c // Degree of parallelism controlled by ICV // $ export OMP_NUM_THREADS=8 // $ ./a.out #pragma omp parallel [parameters] { block } ``` ### Sections in a Parallel Region ```c // Parallel regions can have separate sections #pragma omp sections [parameters] { #pragma omp section { ... block ... } #pragma omp section { ... block ... } ... // an implicit barrier at the end of the sections region/block } ``` ### Parallel Loop ```c // Iterations must be independent!!! // OpenMP would not check dependency!!! #pragma omp for [parameters] for ... // implicit barrier at the end // Unless the parameter 'nowait' is specified ``` ### Available Loop Schedules * static * `Fix sized chunks` (default=n/t) * `Round-robin` fashion * dynamic * `Fix sized chunks` (default=1) * `Distributed one by one` at runtime as chunks finish * guided * Start with `large` chunks, then exponentially `decreasing size` * `Distributed one by one` at runtime as chunks finish * runtime * Controlled at runtime using control variable * auto * Compiler/Runtime can choose ## Data Sharing in OpenMP ### Shared vs. Private Data * **Global variables**: * Shared * **Variables declared within the “dynamic extent” of parallel regions**: * Private * Includes routines called from parallel regions ### Private Data Options ![](https://i.imgur.com/25CgWWF.png) ### First/Last Private Data Options ![](https://i.imgur.com/a1x6Nf4.png) ### Summary: Sharing Attributes of Variables * **`private(var-list)`** * Variables in var-list are private * **`shared(var-list)`** * Variables in var-list are shared * **`default(private | shared | none)`** * Sets the default for all variables in this region * **`firstprivate(var-list)`** * Variables are private * Initialized with the value of the shared copy before the region. * **`lastprivate(var-list)`** * Variables are private * Value of the thread executing the last iteration of a parallel loop in sequential order is copied to the variable outside of the region. ## Synchronization ### Barrier ```c // Each parallel region has an implicit barrier at the end // Can be switched off by adding nowait #pragma omp nowait // Additional barriers can be added when needed #pragma omp barrier ``` ### Master Region ```c // Only the master executes the code block: // * Other threads skip the region // * No synchronization at the beginning of // Possible uses: // * Printing to screen // * Keyboard entries // * File I/Oregion #pragma omp master block ``` ### Single Region ```c // Only a (arbitrary) single thread executes the code block // Possible uses: // * Initialization of data structures #pragma omp single [parameter] block ``` ### Critical Section ```c // Mutual exclusion // All 'unnamed' critical directives map to the same name #pragma omp critical [(Name)] block ``` ### Atomic Statements ```c // Ensures that a specific memory location is updated atomically #pragma ATOMIC expression-stmt ``` ### Simple Runtime Locks ```c omp_init_lock(&lockvar) // initialize a lock omp_destroy_lock(&lockvar) // destroy a lock omp_set_lock(&lockvar) // set lock omp_unset_lock(&lockvar) // free lock logicalvar = omp_test_lock(&lockvar) ``` ### Nestable Locks * Nestable locks can be set multiple times by a single thread. * If the lock counter is 0 after an unset operation, lock can be set by another thread * 例如: * function a 需要 mutex, * function b 也需要 mutex,同時 function a 還會呼叫 function b。 * 如果使用 std::mutex 必然會造成死結。 * 但是使用 std::recursive_mutex (Nestable Lock) 就可以解決這個問題。 ### Ordered Construct ```c #pragma omp for ordered for (...) { S1 #pragma omp ordered { S2 } S3 } ``` ![](https://i.imgur.com/2ijhsKs.png =400x) * [簡易的程式平行化-OpenMP(四)範例 for – Heresy's Space](https://kheresy.wordpress.com/2006/09/15/%E7%B0%A1%E6%98%93%E7%9A%84%E7%A8%8B%E5%BC%8F%E5%B9%B3%E8%A1%8C%E5%8C%96%EF%BC%8Dopenmp%EF%BC%88%E5%9B%9B%EF%BC%89%E7%AF%84%E4%BE%8B-for/) ## Reductions * Aggregate results * Potentially costly and time sensitive operation ### OpenMP Reductions ```c int a=0; #pragma omp parallel for reduction(+: a) for (int j=0; j<4; j++) { a = j; } printf("Final Value of a=%d\n", a); // OMP_NUM_THREADS=4 // 0+1+2+3 = 6 // OMP_NUM_THREADS=2 // 1+3 = 4 ``` ```c int a=0; #pragma omp parallel for reduction(+: a) for (int j=0; j<100; j++) { a = j; } printf("Final Value of a=%d\n", a); // OMP_NUM_THREADS=4 // 24+49+74+99 = 246 ``` ```c int a=0; #pragma omp parallel for reduction(+: a) for (int j=0; j<100; j++) { a += j; } printf("Final Value of a=%d\n", a); // OMP_NUM_THREADS=? // 0+1+2+...+99 = (99*100)/2 = 4950 ```

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully