在CentOS上使用C++实现多线程,你可以使用C++11标准库中的<thread>
头文件。以下是一个简单的示例,展示了如何在CentOS上使用C++11多线程:
sudo yum install gcc-c++
multithread_example.cpp
的文件,并添加以下代码:#include <iostream>
#include <thread>
void print_hello() {
std::cout << "Hello from thread!" << std::endl;
}
int main() {
// 创建一个线程
std::thread t(print_hello);
// 等待线程完成
t.join();
std::cout << "Hello from main thread!" << std::endl;
return 0;
}
g++ -std=c++11 multithread_example.cpp -o multithread_example
./multithread_example
你应该会看到以下输出:
Hello from thread!
Hello from main thread!
这个示例展示了如何在CentOS上使用C++11多线程。你可以根据需要创建更多的线程,并使用std::thread
对象管理它们。注意,为了确保线程安全,你可能需要使用互斥锁(std::mutex
)或其他同步原语来保护共享数据。