在CentOS上使用C++多线程,你需要使用C++11标准库中的<thread>头文件。以下是一个简单的示例,展示了如何在CentOS上使用C++11多线程:
sudo yum install gcc
multithread_example.cpp的C++源文件,并添加以下代码:#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();
std::cout << "Hello from main thread " << std::this_thread::get_id() << std::endl;
return 0;
}
这个示例中,我们定义了一个名为print_hello的函数,它将在线程中运行并打印一条消息。在main函数中,我们创建了两个线程t1和t2,并将它们分别绑定到print_hello函数。然后,我们使用join()方法等待这两个线程完成。
g++ -std=c++11 multithread_example.cpp -o multithread_example
这将生成一个名为multithread_example的可执行文件。
./multithread_example
你应该会看到类似以下的输出:
Hello from thread 140735589875968
Hello from thread 140735581502976
Hello from main thread 140735573129984
这表明你的CentOS系统已经成功运行了C++多线程程序。