在Ubuntu下使用C++编写多线程程序,你可以使用C++11标准库中的<thread>
头文件。下面是一个简单的示例,展示了如何创建和运行多个线程:
#include <iostream>
#include <thread>
// 线程函数
void helloFunction() {
std::cout << "Hello from a thread!" << std::endl;
}
int main() {
// 创建线程
std::thread t(helloFunction);
// 等待线程完成
t.join();
std::cout << "Hello from the main thread!" << std::endl;
return 0;
}
保存代码:将上述代码保存到一个文件中,例如multithread_example.cpp
。
编译代码:使用g++编译器编译代码,并启用C++11标准支持:
g++ -std=c++11 -pthread multithread_example.cpp -o multithread_example
运行程序:
./multithread_example
#include <thread>
:包含C++11标准库中的线程支持。std::thread t(helloFunction);
:创建一个新的线程t
,并在线程中执行helloFunction
函数。t.join();
:等待线程t
完成其任务。如果不调用join
,主线程可能会在子线程完成之前退出,导致未定义行为。你可以创建多个线程并让它们并行执行:
#include <iostream>
#include <thread>
void printNumbers(int start, int end) {
for (int i = start; i <= end; ++i) {
std::cout<< i << " ";
}
std::cout << std::endl;
}
int main() {
// 创建两个线程
std::thread t1(printNumbers, 1, 5);
std::thread t2(printNumbers, 6, 10);
// 等待线程完成
t1.join();
t2.join();
std::cout << "Main thread continues after child threads finish." << std::endl;
return 0;
}
std::mutex
)或其他同步机制来保护共享数据。通过这些基本示例和注意事项,你应该能够在Ubuntu下使用C++编写多线程程序。