簡伯丞
    • 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
    # 2016q3 Homework3(mergesort-concurrent) contributed by <`eeuserp`> ## 開發環境 * CPU: Intel(R) Core(TM) i5-3337U CPU @ 1.80GHz * MEM : 8GB * cache: * L1d cache:32K * L1i cache:32K * L2 cache:256K * L3 cache:3072K * Linux version 4.4.0-21-generic ## POSIX Pthread ### Trace Sample Code >> 注意: 程式碼的實做可能會存在缺失,導致正確性的議題,請一併提出 [name=jserv] * * threadpool.h ```clike= typedef struct _task { //task 的資料結構 void (*func)(void *); void *arg; struct _task *next, *last; } task_t; ``` ```clike= typedef struct { //task queue 的資料結構 task_t *head, *tail; pthread_mutex_t mutex; pthread_cond_t cond; uint32_t size; //宣告一個 8 byte 的非負整數 } tqueue_t; ``` ```clike= typedef struct { //thread pool 的資料結構 pthread_t *threads; //宣告 thread id uint32_t count; tqueue_t *queue; //宣告 task queue } tpool_t; ``` * threadpool.c ```clike= int tqueue_init(tqueue_t *the_queue) //初始化 task queue { the_queue->head = NULL; the_queue->tail = NULL; pthread_mutex_init(&(the_queue->mutex), NULL); //初始化互斥鎖 pthread_cond_init(&(the_queue->cond), NULL); //初始化條件變量 the_queue->size = 0; return 0; } ``` ```clike= task_t *tqueue_pop(tqueue_t *the_queue) //把 thread 從 task queue pop 到 thread pool { task_t *ret; pthread_mutex_lock(&(the_queue->mutex)); //占有互斥鎖(阻塞操作) ret = the_queue->tail; if (ret) { the_queue->tail = ret->last; //ret 被 pop 掉了 , 所以 queue 的尾端 是ret 的上一筆資料 if (the_queue->tail) { the_queue->tail->next = NULL; } else { //queue 的尾端沒東西 , 代表整個 queue 都是空的 the_queue->head = NULL; } the_queue->size--; } pthread_mutex_unlock(&(the_queue->mutex));//解鎖 return ret; } ``` ```clike= int tqueue_push(tqueue_t *the_queue, task_t *task) { pthread_mutex_lock(&(the_queue->mutex)); task->last = NULL; //要 push 進 queue 的 task 後面沒有東西 task->next = the_queue->head; //要 push 進 queue 的 task 的下一筆資料 目前在 queue 的頭 if (the_queue->head) the_queue->head->last = task; // 要 push 進 queue 的 task排在目前最後一筆資料(在 queue 的頭)的後面 the_queue->head = task; // 要 push 進 queue 的 task 設為 queue 的頭 if (the_queue->size++ == 0) //假如 queue 為空 the_queue->tail = task; //要 push 進 queue 的 task 設為 queue 的尾 pthread_mutex_unlock(&(the_queue->mutex)); return 0; } ``` ```clike= int tpool_init(tpool_t *the_pool, uint32_t tcount, void *(*func)(void *)) { the_pool->threads = (pthread_t *) malloc(sizeof(pthread_t) * tcount); the_pool->count = tcount; the_pool->queue = (tqueue_t *) malloc(sizeof(tqueue_t)); tqueue_init(the_pool->queue); pthread_attr_t attr; //宣告 thread 屬性 pthread_attr_init(&attr); //初始化 threa 屬性變數 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);//設定 thread 的 detachstate 屬性為 joinable for (uint32_t i = 0; i < tcount; ++i) pthread_create(&(the_pool->threads[i]), &attr, func, NULL); pthread_attr_destroy(&attr);//刪除執行緒的屬性,用無效值覆蓋 return 0; } ``` `pthread_attr_setdetachstate` : thread 可以分為 joinable 或是 detached。joinable thread 可以被其他 thread回收其資源或是銷毀。detached thread不能被其他 thread回收其資源或是銷毀,其占用資源在終止時由系統自動釋放。thread的detachstate決定一個thread以什麼樣的方式終止自己。 `pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE)` : 將 thread 設為 joinable thread , 原有的 thread 等待建立的 thread 結束。只有當 pthread_join() 函式返回時,建立的thread才算終止,才能釋放自己所占用的資源。建立 thread 時 , default 為 joinable thread ,所以第 9 行註解掉後實測可以正常執行 `pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED)` : 將 thread 設為 detached thread , detached thread 沒有被其他 thread 等待 , 自己執行結束 , thread 立即中止 , 馬上釋放佔用的系統資源。 ## Code Refactoring * threadpool.c * `tpool_init` 和 `tpool_free` 中的迴圈的更新值 `++i` 改成 `i++` * `++i` 是先執行 `i=i+1` 再執行迴圈內的程式碼 , `i++` 是先執行迴圈內的程式碼再執行`i=i+1` * `tpool_init` 中的 `pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);` 可以刪除 , 因為 <s>創建</s> 建立 thread 時 , default 為 joinable thread * `tqueue_pop` 和 `tqueue_push` 中 task 從 head push 進 queue ,從 tail pop 出queue 這是錯的。正確的應是從 tail push 進 queue ,從 head pop 出 queue >> create 的繁體中文翻譯為「建立」,而非創建,後者是對岸術語 [name=jserv] >> 我以後參考對岸資料會多加注意,謝謝老師[name=eeuserp] >> `++i`或`i++`對for迴圈主體沒差吧 [(reference)](http://stackoverflow.com/questions/4706199) [name=mingnus] ## 參考資料 * [pthread_attr_setdetachstate 函數使用](http://blog.csdn.net/sjin_1314/article/details/8023575) * [argc, argv 解析用法](http://jyhshin.pixnet.net/blog/post/26588000-argc,-argv-%E8%A7%A3%E6%9E%90%E7%94%A8%E6%B3%95) * [Queue (abstract data type) - Wikipedia ](https://en.wikipedia.org/wiki/Queue_(abstract_data_type))

    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