iT邦幫忙

2026 iThome 鐵人賽

DAY 17
0
自我挑戰組

韌體工程師的不只 0x10 個問題系列 第 17

Day 17 - 執行緒超入門

  • 分享至 

  • xImage
  •  

執行緒(thread)是個非常重要的觀念,在實際操作前,先來了解不同名詞之間的關係。

  • 程式(program):指的是「靜態」程式檔案,尚未被執行。
  • 行程/程序(process):是「正在執行」的程式,作業系統會為其分配記憶體等資源,且每個行程間彼此隔離。
  • 執行緒(thread):行程內「實際執行程式碼」之單位,一個行程可能有一個執行緒或多個執行緒,若有多個執行緒,每個執行緒都共享相同的記憶體等資源。

三者間的關係圖如下:

程式(program)
     ↓ 開始運行
行程/程序(program)   
 |
 | ┌─> 執行緒一(thread 1)
 └─|
   └─> 執行緒二(thread 2)

如何在 C++ 建立執行緒?

從 C++ 11 起,可以直接用標頭檔 <thread> 來操作執行緒,範例用法如下:

#include <iostream>
#include <thread>

void printMessage() {
    std::cout << "Hello from the new thread!" << std::endl;
}

int main()
{
    // 在還沒有新執行緒時,只有主執行緒執行這裡
    std::cout << "Originally in the main thread." << std::endl;

    // 建立一個新執行緒物件 myThread,並指定 printMessage 為執行內容
    std::thread myThread(printMessage);
    
    // 這時主執行緒與新執行緒同時進行

    // 用 join() 使主執行緒等待 myThread 這個新執行緒執行完畢
    myThread.join();
    
    // 這時只有新執行緒在跑,主執行緒暫停

    // 新執行緒 myThread 結束後,主執行緒繼續執行,印出下列訊息
    std::cout << "Back in the main thread." << std::endl;

    return 0;
}

程式碼執行流程如下:

  1. 一開始只有主執行緒,執行 main() 函數。
  2. 顯示 main() 函數的 std::cout << "Originally in the main thread." << std::endl;
  3. 建立新執行緒 myThread,其內容為 printMessage() 函數;此時主執行緒與新執行緒同時進行。
  4. 到了 .join() ,主執行緒會等待新執行緒執行完畢。
  5. 新執行緒執行完畢,回到主執行緒,顯示 main() 函數的 std::cout << "Back in the main thread." << std::endl;

執行結果如下:

Originally in the main thread.
Hello from the new thread!
Back in the main thread.

在上述程式碼中,共有執行 main() 函數的主執行緒,以及 myThread() 這個新執行緒,因此為多執行緒,透過 join() 協調。

如果沒有 join(),則新執行緒在還沒執行完時,即可能因主執行緒執行完畢而跟著被強制終止,使程式提早結束。

參考資料

  1. How to Create a Thread in C++? (GeeksforGeeks)
  2. Multithreading | How to Create and Manage Threads in C++ (Shreyos Ghosh on DEV Community)
  3. 多執行緒(李謦伊 Medium)
  4. 多執行緒 — C++ Thread — C++ Thread(李謦伊 Medium)
  5. Understanding C++ Threads: A Complete Guide (Madhawa Polkotuwa Medium)

上一篇
Day 16 - 硬體資源配置常見的坑
下一篇
Day 18 - volatile 關鍵字
系列文
韌體工程師的不只 0x10 個問題19
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言