FANFNA
    • 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
    • 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 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
    # CH4 thread :::spoiler [TOC] ::: ## 一、thread 簡介 :::success thread 是 OS 能夠進行運算排程的最小單位,它被包含在 process 之中,是 process 中的實際運作單位。 - thread 是 OS 分配 CPU 時間的對象。 - process 是 OS 分配資源的對象。 ::: :::info thread 擁有以下內容 : - Thread ID - Thread State - Program counter - Register set - Stack ::: :::info process 內的 threads 彼此共享 : - code Section - data Section - OS Resources ::: :::warning **(Code section + Data section = memory space, Address space, Heap memory)** ::: :::info process 中有 multi-thread 的好處: - 應答 : 允許程式中的某部份被中斷或是執行得非常久時,該程式仍然可以繼續執行。 - 資源分享 : 分享 code、data 和 OS 資源 - 經濟 : 輕量化的 process。(context switch 一個 thread 比 process 快約 5 倍,建立一個 thread 比 process 快約 13 倍。) - 可使用多處理器架構 : 使用多核心。 ::: ## 二、Multi-threading 介紹 ### 1. user threads and kernel threads :::success **User threads** 在 user mode 下進行,OS 不知道有這些 thread 存在不需要 OS 介入管理。 - 優點:產生、管理成本較低 - 缺點:若 process 的 user thread 發出鎖定的 system call 且 kernel 是 single thread 則整個 process 被鎖住。 ::: :::info 常見的 user thread - Pthreads (POSIX threads) - Win32 threads - Java threads ::: :::success **b. Kernel thread** 在 kernel mode 下進行,OS 知道有這些 thread 存在,由 OS 介入管理。 ::: :::info 常見的 kernel threads - Windows XP/2000 - Solaris - Linux - Tru64 UNIX ::: :::warning **[Multi-threads 例題]** 有兩個 Process P~A~ 與 P~B~,P~A~ 三 條thread、P~B~ 兩條thread,若 OS 採平均分配原則來分配 CPU Time,則 P~A~ 與 P~B~ 各分多少 % 之 CPU Time? - User thread - Kernel thread :::spoiler Ans : Kernel 不知道有 user thread,只知道有 P~A~ 與 P~B~ 兩個 process。P~A~ 與 P~B~ 各分到 50% 的 CPU Time。 有 5 條 thread 欲分配,每條可分到 20% 的 CPU time。 P~A~ 分到 3×20% = 60% 的 CPU time。 P~B~ 分到 2×20% = 40% 的 CPU time 。 ::: ### 2. Multi-threading models :::info a. **Many-to-one Model** 系統容易被 single thread 執行鎖死 沒有平行化 可攜性佳 b. **One-to-one Model** 成本較高 產生一個 user thread 時,需連帶產生一個 kernel thread,而 kernel thread 會對程式的執行產生一些額外的負擔。因此此模式限制執行緒產生的個數。 c. **Many-to-Many Model** 系統不會被 single thread 執行鎖死 比 one-to-one 經濟 i/o bound thread 要有 kernel thread 對應,但是不會讓執行的核心忙碌。所以想讓執行的核心忙碌要再加等量的 kernel thread ::: ::: :::warning [用心去感覺] When you write multithreaded programs, It should not be assumed that which model is adopted by the thread library! ::: :::danger 程式設計師寫 multithread 程式是呼叫 **thread API** 來撰寫 (也就是 **thread libraries**),而該 API 內部實作是用哪一種模型 (**Many-to-one**, **One-to-one** 或 **Many-to-Many**) 在規範中是沒有規定的,所以程式設計師不應該預設內部是某一種模型,以避免預期之外的錯誤。 ::: ## 三、Threading Issue :::info a.**Semantics of fork() and exec()**,fork 呼叫一個 thread 或 all thread? Undefined. maybe the following - 只 fork 該 thread : 當 child 做工作與 parent 不同 - fork 整個 process : 當 child 所做的工作與 parent 相同 ::: :::info b. **Signal handling** - Signal type : - synchronous signal, ex : illegal memory access,division by zero - asynchronous signal, ex : control+c - Signal handler : - default 由編輯器自動載入預設的訊號處理 - user-defined 自行定義訊號的處理 ::: :::danger [補充] process 或裝置通知 kernel -> interrupt;kernel 通知 process -> signal。[IO](https://medium.com/@clu1022/%E6%B7%BA%E8%AB%87i-o-model-32da09c619e6) ::: :::info c. **Thread cancellation** - asynchronous cancellation : 立刻取消 - deferred cancellation : 一個時間周期到才會取消 - actual cancellation : 根據thread狀態取消 ::: :::info d. **Thread pools** 產生多個thread 並等待執行,採取此方法的原因使用現有 thread 比新產生一個thread 快。此法等待執行的 thread 數目前依目前 thread pool 大小決定。 ::: :::info e. **TLS (thread-local storage)** TLS 要解決的問題,並不是 Thread 之間資源共享的問題,而是 Thread 本身資源共享的問題。TLS 是在 thread 中佈置一塊空間,並讓 thread 外面可以觀測。 ::: :::info f. **Light weight process (LWP)** 介於 user-level thread 和 kernel-level thread 的資料結構,用來提供一個 virtual process 讓應用程式 thread 做排程,支援多個 User-level Thread 對應到一個 kernel thread,屬於 kernel-level thread。 ::: :::info g. **Thread libraries : pthreads** Pthreads (POSIX threads) 是依據 ieee 1003.1c 標準定義的 thread 標準,定義了創建和操縱 thread 的一套 API,可用在 user-level 和 kernel-level,常用在一般 Unix 作業系統。 ::: :::info h. **Implicit threading methods** - thread pools - openMP - grand central dispatch - TBB (threading building blocks) :::

    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