sunfrancis12
    • 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 New
    • Engagement control
    • Make a copy
    • 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 Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy 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
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # 第一題:第六章第七章同步工具的整理與比較 ## Lock Lock是一種同步機制,旨在確保在多線程(multi thread)的環境中,同一時間只能有一個thread訪問該資源 鎖的使用可以避免data race(不同的thread同時讀寫共享變數),從而保證程式的正確性。 ![](https://i.imgur.com/dwZxhLg.png =60%x) ## Mutex Lock 用於確保同一時間只有一個process可以進入臨界區(critical section)。 ```c= acquire(){ while (!available) ; /* busy wait */ available = false; } release(){ available = true; } do{ acquire() critical section release() remainder section }while(true); ``` **缺點** * 會有**busy waiting**的情況發生(process一直檢查condition是否為true) ## Semaphore 實作了 **wait()** 和 **signal()**,並把process分成**waiting, ready state(queue)** * ready state(queue) * 接著要被執行的process * waiting state(queue) * 等待中的process * wait() * 確保只有一個process可以修改該資料 * **block** * 將process放至waiting queue * signal() * **wakeup** * 將一個process從waiting queue放至ready queue ```c= typedef struct{ int value; struct process *list; } semaphore; wait(semaphore *S) { S->value--; if (S->value < 0) { add this process to S->list; block(); } } signal(semaphore *S) { S->value++; if (S->value <= 0) { remove a process P from S->list; wakeup(P); } } ``` **缺點** * 可能會有deadlock發生 ### semaphore種類 * Counting semaphore * 用於多個process * Binary semaphore * 只有0, 1,適用於2個porcess(概念類似Mutex lock) ## Monitor ### Abstract Data Type (ADT) * Encapsulates **data** with a set of **functions** to operate on that data that are independent of any specific implementation of the ADT ### Monitor * Monitor會將要共享資源和訪問這些資源的方法封裝在一個對象(ADT)中。 * 每次只有一個process可以訪問Monitor內部的資源 * 條件變量(Condition Variable) * Monitor常配合條件變量使用,允許process在等待某個條件時進入waiting queue。 ![image](https://hackmd.io/_uploads/B1ITXSwXkg.png) ## Hardware Support for Synchronization ### Memory barriers Memory barriers用於**強制** CPU 和編譯器**按照特定順序執行記憶體操作**,從而避免因記憶體重排序(Memory Reordering)導致的問題。 **記憶體重排序** * 現代 CPU 和編譯器為了優化性能,可能會重新排序讀/寫操作。 在多執行緒環境中,**重排序可能導致資料一致性問題**。 **Memory model** * Strongly ordered * 硬體或編譯器**不會改變**讀寫**指令的順序** * Weakly ordered * 處理器和編譯器**可以自由地重新排序記憶體操作**,只要這些操作不違反程式執行結果 ### Atomic variables Atomic variables是一種變數類型,保證在多執行緒環境中對該變數的操作是不可分割的(atomic),不會再分給其他的thread,可以避免data race ### hardware instructions(Atomic operation) 類似Atomic variables的概念,Atomic operation不會被其他thread打斷,用於保證多線程環境中的同步。 **test_and_set** * 用途 * 表示lock是否已經被佔用 * 回傳值 * 返回變數的原始值,並將其設置為新值 ```java boolean test_and_set (boolean *target) { boolean rv = *target; *target = TRUE; return rv: } do { while (test_and_set(&lock)) ; /* do nothing */ //只有當lock是false時才能進入critical section /* critical section */ lock = false; /* remainder section */ } while (true); ``` **compare_and_swap** * 用途 * 用於實現無鎖(lock-free)操作,**實現比較並交換**的操作 * compare_and_swap()不會被其他線程打斷,因此在不使用lock的情況下保證操作的正確性。 * 回傳值 * 返回變數的原始值,並指示操作是否成功 * lock初始值為0 ```java int compare_and_swap(int *value, int expected, int new_value) { int temp = *value; if (*value == expected) *value = new_value; return temp; } do { while (compare_and_swap(&lock, 0, 1) != 0) ; /* do nothing */ //只有當lock是0時才能進入critical section /* critical section */ lock = 0; /* remainder section */ } while (true); ``` > 來源:https://hackmd.io/@2020OS/ryMVc6u9L ### Transactional Memory Transactional Memory旨在簡化多線程程序中的同步問題,尤其是當多個線程需要操作共享資源時,他會把一段的operations都變成atomic operations,要麼全部執行成功,要麼全部回滾(rolled back) * Transactional Memory會透過update()修改shared data * 如果有operations執行失敗,則會需要在全部重做一次(rolled back) ```c= void update ( ) { atomic { // modify shared data } } ``` # 第二題:bounded buffer 不同版本的解法 我們也可以透過Monitor來解決bounded buffer的問題 Mointor可以控制當進入或結束一個process的時候: * 進入一個process時: * 發現buffer剩下一個則signal(empty),wakeup consumer use source * 發現buffer滿了則wait(full),block producer release source * 結束一個process時: * 發現buffer為空則wait(empty),block consumer use source * 發現buffer差一個就滿了則signal(full),wakeup producer release source **程式碼範例:** ```c= monitor ProducerConsumer condition full, empty; int count; procedure enter(); { if (count == N) wait(full); // if buffer is full, block put_item(widget); // put item in buffer count = count + 1; // increment count of full slots if (count == 1) signal(empty); // if buffer was empty, wake consumer } procedure remove(); { if (count == 0) wait(empty); // if buffer is empty, block remove_item(widget); // remove item from buffer count = count - 1; // decrement count of full slots if (count == N-1) signal(full); // if buffer was full, wake producer } count = 0; end monitor; Producer(); { while (TRUE) { make_item(widget); // make a new item ProducerConsumer.enter; // call enter function in monitor } } Consumer(); { while (TRUE) { ProducerConsumer.remove; // call remove function in monitor consume_item; // consume an item } } ``` > 來源:https://denninginstitute.com/modules/ipc/purple/prodmon.html

    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