在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++多线程的基本方法。