我会详细讲解C++多线程编程的攻略。对于多线程编程,一般分为以下几个步骤:
1. 包含头文件
要进行多线程编程,需要包含头文件<thread>
。
#include <thread>
2. 创建线程
使用std::thread
类创建一个线程,并将需要执行的函数作为参数传入。
void my_func() {
// 线程要执行的代码
}
std::thread my_thread(my_func); // 创建线程并传入函数
3. 线程执行
创建好线程后,使用std::thread
类的join()
方法等待线程执行完成。
my_thread.join(); // 等待线程执行完成
4. 线程参数传递
可以通过向线程函数传递参数来进一步使用线程的能力。线程函数参数可以是任何类型的值或引用,包括C++对象。
void my_func(int arg1, double arg2, std::string arg3) {
// 线程要执行的代码
}
int my_arg1 = 5;
double my_arg2 = 1.23;
std::string my_arg3 = "Hello";
std::thread my_thread(my_func, my_arg1, my_arg2, my_arg3); // 传递参数创建线程
示例1:打印数字
下面是一个简单的示例,展示如何使用多线程并行打印数字。
#include <iostream>
#include <thread>
void print_num(int num) {
std::cout << num << std::endl;
}
int main() {
std::thread t1(print_num, 1);
std::thread t2(print_num, 2);
std::thread t3(print_num, 3);
t1.join();
t2.join();
t3.join();
return 0;
}
示例2:并行计算
下面是一个示例,演示如何将计算任务分为多个线程并行计算,并将计算结果汇总。
#include <iostream>
#include <thread>
#include <vector>
#include <numeric>
void count_sum(std::vector<int>& data, int start, int end, int& result) {
result = std::accumulate(data.begin() + start, data.begin() + end, 0);
}
int main() {
std::vector<int> data = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
const int thread_num = 4;
std::vector<std::thread> threads;
std::vector<int> results(thread_num);
const int data_size = data.size();
for(int i=0; i<thread_num; i++) {
int start = i * (data_size / thread_num);
int end = (i + 1) * (data_size / thread_num);
if(i == thread_num-1) {
end = data_size;
}
threads.emplace_back(count_sum, std::ref(data), start, end, std::ref(results[i]));
}
for(auto& t : threads) {
t.join(); // 等待线程执行完成
}
int sum = std::accumulate(results.begin(), results.end(), 0); // 将每个线程计算结果汇总
std::cout << "Sum of vector = " << sum << std::endl;
return 0;
}
以上就是C++多线程编程的基本攻略及两个示例。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:C++多线程编程详解 - Python技术站