在C++中,可以使用標準庫 <thread>
來實現多線程編程。以下是一個簡單的示例,展示了如何在Linux環境下使用C++11的多線程功能:
#include <iostream>
#include <thread>
// 線程函數
void helloFunction() {
std::cout << "Hello from a thread!" << std::endl;
}
int main() {
// 創建一個線程
std::thread t(helloFunction);
// 等待線程完成
t.join();
std::cout << "Hello from the main thread!" << std::endl;
return 0;
}
要編譯這個程序,你需要使用支持C++11的編譯器,并且鏈接線程庫??梢允褂靡韵旅睿?/p>
g++ -std=c++11 -pthread your_program.cpp -o your_program
然后運行生成的可執行文件:
./your_program
包含頭文件:
#include <thread>
這個頭文件包含了線程相關的定義和函數。
線程函數:
void helloFunction() {
std::cout << "Hello from a thread!" << std::endl;
}
這是一個普通的函數,將被用作線程的執行體。
創建線程:
std::thread t(helloFunction);
這行代碼創建了一個新的線程 t
,并將 helloFunction
作為其執行體。
等待線程完成:
t.join();
調用 join()
方法會阻塞主線程,直到 t
線程完成執行。
std::mutex
)來保護共享資源。thread_local
關鍵字來聲明線程局部存儲變量。#include <iostream>
#include <thread>
#include <mutex>
std::mutex mtx; // 全局互斥鎖
void printMessage(const std::string& msg) {
std::lock_guard<std::mutex> lock(mtx); // 自動管理鎖
std::cout << msg << std::endl;
}
int main() {
std::thread t1(printMessage, "Hello from thread 1!");
std::thread t2(printMessage, "Hello from thread 2!");
t1.join();
t2.join();
return 0;
}
在這個示例中,printMessage
函數使用 std::lock_guard
來自動管理互斥鎖,確保在同一時間只有一個線程可以訪問 std::cout
。
通過這些基本概念和示例,你應該能夠在Linux環境下使用C++實現多線程編程。