陳致佑
    • 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
    # Pthread 探討 [參考pthreads](https://computing.llnl.gov/tutorials/pthreads/) [pthread介紹](http://www.cse.iitd.ernet.in/~dheerajb/Pthreads/Document/Pthreads_Information.html) Programs having the following characteristics may be well suited for pthreads: * Work that can be executed, or data that can be operated on, by multiple tasks simultaneously: * Block for potentially long I/O waits * Must respond to asynchronous events * Some work is more important than other work (priority interrupts) > 工作可以被多任务同时执行或者数据可以被同时操作 潜在的长时间I/O等待阻塞 必须响应异步事件 ### Compiling Threaded Programs ![](https://i.imgur.com/BS4bNku.png) The subroutines which comprise the Pthreads API can be informally grouped into four major groups: 分為4個主要的設計:執行序管理、互斥鎖、條件變量、(同步問題) * 1.Thread management: Routines that work directly on threads - creating, detaching, joining, etc. They also include functions to set/query thread attributes (joinable, scheduling etc.) * 2.Mutexes: Routines that deal with synchronization, called a “mutex”, which is an abbreviation for “mutual exclusion”. Mutex functions provide for creating, destroying, locking and unlocking mutexes. These are supplemented by mutex attribute functions that set or modify attributes associated with mutexes. * 3.Condition variables: Routines that address communications between threads that share a mutex. Based upon programmer specified conditions. This group includes functions to create, destroy, wait and signal based upon specified variable values. Functions to set/query condition variable attributes are also included. * 4.Synchronization: Routines that manage read/write locks and barriers. ### Thread Management * Creating and Terminating Threads * Initially, your main() program comprises a single, default thread. All other threads must be explicitly created by the programmer. * `pthread_create` creates a new thread and makes it executable * `pthread_exit` routine allows the programmer to specify an optional termination status parameter. This optional parameter is typically returned to threads "joining" the terminated thread * `pthread_join` subroutine blocks the calling thread until the specified threadid thread terminates. >* thread creat / exit 建立和終結 exit可以回傳值到 join ,join會先停在程式間直到接收到exit回傳值。 >* pthread_join用來等待一個thread的結束,也就是主thread 中要是加了這段 code,就會在加code的位置停住,直到這個 thread 執行完成後才會繼續。 >* pthread_exit用來強制關閉一個thread(並非執行完畢退出),通常用在 thread 內部。 >* 结合用法: >一般都是 pthread_exit 在 thread 内退出,然後回傳一個值。接著就會回到主程式的pthread_join了(因為一直在等你结束),這個回傳值會直接送到pthread_join,實現了主thread和 其他 thread 的通信。 ![](https://i.imgur.com/8JZpntD.png) ### Mutexes A typical sequence in the use of a mutex is as follows: * Create and initialize a mutex variable * Several threads attempt to lock the mutex * Only one succeeds and that thread owns the mutex * The owner thread performs some set of actions * The owner unlocks the mutex * Another thread acquires the mutex and repeats the process * Finally the mutex is destroyed #### mutex & semaphore 的作用和區別 * Semaphore 和 Mutex 的差異 Mutex 與 Semaphore 都是用在保護 critical section,確保多個 threads 平行運作並存取資源時,執行結果不會因為執行程序的時間先後的影響而導致錯誤。 * Mutex(Mutual Exclusion) 與 Semaphore 的差別在於: Mutex is a key to a toilet. Semaphore is the number of free identical toilet keys. * Mutex thread 使用 mutex 時,thread 的運作是持有 Mutex,執行 critical section 來存取資源,然後釋放 Mutex. Mutex 就像是資源的一把鎖。 * Semaphore thread 使用 semaphore 時,thread 總是發出信號(signal),或者總是接收信號(wait),同一個 thread 不會先後進行 signal 與 wait。也就是說,thread 要嘛當 producer,要嘛當 consumer,不能兩者都是。Semaphore 是為了保護 pthread 的執行同步性。 * Critical Section [參考](http://ccu-cs-os2009s-495410049.blogspot.tw/2009/06/os-critical-section.html) 指當多個thread可能同時存取的記憶體、變數或函數的情況,它的作用是用於在多執行緒環境中保護資源,而通常這種要受保護的程式區段稱為 Critical Section 。 在程式裡有可能有兩個 thread (可看成一個小小的function)同時存取一個global variable(全域變數)(或函數),這時後,因為程式的需要,thread 不想被其他程式中斷(不被其他thread插入影響),所以必須要一口起執行完畢,而該需要一口氣執行完的程式區段,所以需要設定 Critical Section,以保護目前執行的 thread 不被其他影響。 * 控制critical section執行之機制必須滿足下列三個要求: (1)Mutual exclusion:不允許兩個以上的process同時在對應的critical section中執行。 (2)Progress:若沒有process在對應的critical section中執行,則控制的機制不能阻擋請求進入critical section之process進入critical section。 (3)Bounded waiting:控制機制必須使等待進入critical section之process在有限時間內進入critical section。 ### Condition variables [參考](http://blog.xuite.net/mb1016.flying/linux/26293042-%E8%BD%89%E8%B2%BC%3A+pthread+%E8%A7%A3%E8%AE%80(%E4%B8%89)) Condition variables provide yet another way for threads to synchronize. While mutexes implement synchronization by controlling thread access to data, condition variables allow threads to synchronize based upon the actual value of data. Without condition variables, the programmer would need to have threads continually polling (possibly in a critical section), to check if the condition is met. This can be very resource consuming since the thread would be continuously busy in this activity. A condition variable is a way to achieve the same goal without polling. A condition variable is always used in conjunction with a mutex lock. > 條件變量是利用線程間共享的全局變量進行同步的一種機制,主要包括兩個動作:一個線程等待"條件變量的條件成立"而掛起;另一個線程使"條件成立"(給出條件成立信號)。為了防止競爭,條件變量的使用總是和一個互斥鎖結合在一起。 * `pthread_cond_signal` routine is used to signal (or wake up) another thread which is waiting on the condition variable. It should be called after mutex is locked, and must unlock mutex in order for pthread_cond_wait() routine to complete. * `pthread_cond_wait` blocks the calling thread until the specified condition * `pthread_cond_broadcast` routine should be used instead of pthread_cond_signal() if more than one thread is in a blocking wait state. ![](https://i.imgur.com/NqbcTlm.png) ### 建立 Thread pool Works with pthreads only, but API is intentionally opaque to allow other implementations (Windows for instance). * Starts all threads on creation of the thread pool. * Reserves one task for signaling the queue is full. * Stops and joins all worker threads on destroy. ![](https://i.imgur.com/SGgqG0R.png)

    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