在Ubuntu下进行C++多线程编程,你可以使用C++11标准库中的<thread>头文件。以下是一个简单的示例,展示了如何在Ubuntu下使用C++11创建和运行多个线程。
首先,确保你的编译器支持C++11。在编译时,需要添加-std=c++11参数。例如,如果你的源代码文件名为main.cpp,可以使用以下命令进行编译:
g++ -std=c++11 main.cpp -o main 接下来,创建一个名为main.cpp的文件,并添加以下代码:
#include <iostream> #include <thread> // 线程函数 void hello_thread() { std::cout << "Hello from thread!" << std::endl; } int main() { // 创建线程 std::thread t(hello_thread); // 等待线程完成 t.join(); std::cout << "Hello from main thread!" << std::endl; return 0; } 在这个示例中,我们包含了<iostream>和<thread>头文件。我们定义了一个名为hello_thread的函数,它将在新线程中运行。在main函数中,我们使用std::thread类创建了一个新线程,并将hello_thread函数作为参数传递给它。然后,我们使用join()方法等待线程完成。最后,我们在主线程中输出一条消息。
要运行此程序,请在终端中输入以下命令:
./main 你应该会看到以下输出:
Hello from thread! Hello from main thread! 这表明我们的多线程程序已成功运行。你可以根据需要修改hello_thread函数以执行你需要的任务。