在Ubuntu中,使用C++11及更高版本可以輕松地實現多線程。C++11引入了一個新的庫 <thread>,它提供了創建和管理線程的功能。以下是一個簡單的示例,展示了如何在Ubuntu中使用C++11多線程:
-std=c++11參數。例如,如果你的源代碼文件名為main.cpp,可以使用以下命令進行編譯:g++ -std=c++11 main.cpp -o main -pthread
main.cpp的源代碼文件,并添加以下內容:#include <iostream>
#include <thread>
// 定義一個簡單的線程函數
void hello_thread() {
std::cout << "Hello from a thread!" << std::endl;
}
int main() {
// 創建一個線程對象,并將其綁定到hello_thread函數
std::thread t(hello_thread);
// 等待線程完成
t.join();
std::cout << "Hello from the main thread!" << std::endl;
return 0;
}
在這個示例中,我們首先包含了<iostream>和<thread>頭文件。然后,我們定義了一個簡單的線程函數hello_thread,它只是輸出一條消息。在main函數中,我們創建了一個std::thread對象t,并將其綁定到hello_thread函數。最后,我們使用join()方法等待線程完成。
編譯并運行這個程序,你將看到以下輸出:
Hello from a thread!
Hello from the main thread!
這表明我們的線程已經成功運行并與主線程并行執行。你可以根據需要創建更多的線程,并根據實際需求調整線程函數。