在CentOS上使用C++多线程,你需要遵循以下步骤:
sudo yum groupinstall "Development Tools"
接下来,安装C++标准库和其他必要的库:
sudo yum install cpp libstdc++-devel
multithread_example.cpp
的文件,并添加以下代码:#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;
}
这个简单的示例程序创建了两个线程,它们都调用print_hello
函数并打印一条消息。
g++ -o multithread_example multithread_example.cpp -pthread
./multithread_example
你应该看到来自两个线程的消息。
注意:C++11引入了<thread>
库,它提供了跨平台的线程支持。在上面的示例中,我们使用了C++11的线程功能。如果你使用的是较旧的C++标准,你可能需要使用特定于平台的线程库,如POSIX线程(pthreads)。