在Linux應用中使用C++多線程,你可以使用C++11標準庫中的<thread>
頭文件
#include <iostream>
#include <thread>
void print_hello() {
std::cout << "Hello from thread " << std::this_thread::get_id() << std::endl;
}
int main() {
// 創建兩個線程
std::thread t1(print_hello);
std::thread t2(print_hello);
// 等待線程完成
t1.join();
t2.join();
return 0;
}
在這個示例中,我們創建了兩個線程t1
和t2
,它們都執行print_hello
函數。std::this_thread::get_id()
函數用于獲取當前線程的ID。
要在Linux上編譯這個程序,你需要使用支持C++11的編譯器,例如g++。使用以下命令編譯程序:
g++ -std=c++11 -pthread your_source_file.cpp -o your_executable
注意,我們在編譯命令中添加了-std=c++11
和-pthread
選項。-std=c++11
告訴編譯器使用C++11標準,而-pthread
選項啟用了多線程支持。
編譯完成后,你可以運行生成的可執行文件:
./your_executable
這將輸出類似以下內容:
Hello from thread 1234567890
Hello from thread 9876543210
這里,你可以看到兩個線程分別打印了不同的消息。這就是如何在Linux應用中使用C++多線程的基本方法。