在Ubuntu下进行C++多线程编程,你需要使用C++11标准库中的<thread>
头文件。下面是一个简单的示例,展示了如何在Ubuntu下使用C++11多线程:
-std=c++11
参数。例如,如果你的源代码文件名为main.cpp
,可以使用以下命令进行编译:g++ -std=c++11 main.cpp -o main
#include <iostream>
#include <thread>
void print_numbers() {
for (int i = 1; i <= 10; ++i) {
std::cout << "Thread 1: "<< i << std::endl;
}
}
int main() {
// 创建两个线程
std::thread t1(print_numbers);
std::thread t2(print_numbers);
// 等待线程完成
t1.join();
t2.join();
return 0;
}
g++ -std=c++11 main.cpp -o main
./main
注意:在实际应用中,你可能需要处理线程同步和互斥问题。C++11提供了<mutex>
头文件,其中包含了std::mutex
、std::lock_guard
等工具来帮助你实现线程同步。
例如,如果你需要确保两个线程不会同时访问共享资源,可以使用std::mutex
来实现互斥:
#include <iostream>
#include <thread>
#include <mutex>
std::mutex mtx;
void print_numbers(int id) {
for (int i = 1; i <= 10; ++i) {
mtx.lock(); // 加锁
std::cout << "Thread " << id << ": "<< i << std::endl;
mtx.unlock(); // 解锁
}
}
int main() {
std::thread t1(print_numbers, 1);
std::thread t2(print_numbers, 2);
t1.join();
t2.join();
return 0;
}
这个示例中,我们使用std::mutex
对象mtx
来确保两个线程不会同时访问std::cout
。在访问共享资源之前,我们调用mtx.lock()
来加锁,访问完成后调用mtx.unlock()
来解锁。这样可以确保每次只有一个线程可以访问共享资源。