嗨,大家好!我是一行。今天咱们来认识超棒的 TBB 库,它能让 C++程序高效地处理并发任务,就像给你的代码装上了多个小引擎,同时发力,飞速运行。无论是处理大量数据还是多任务并行,它都能轻松应对,快来一起探索吧!
一、TBB 基础概念与任务并行TBB 里的任务并行就像是一群小助手同时干活。咱们先来看个简单例子,假设有一堆数字要相加。
#include <iostream>
#include <tbb/tbb.h>
// 定义一个求和的函数对象
class SumTask {
public:
int* array;
int size;
int result;
SumTask(int* a, int s) : array(a), size(s), result(0) {}
// 重载 operator() 来定义任务的执行逻辑
void operator()(const tbb::blocked_range<int>& range) const {
for (int i = range.begin(); i < range.end(); i++) {
result += array[i]; // 把范围内的数字相加
}
}
};
int main() {
int numbers[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int size = sizeof(numbers) / sizeof(int);
// 创建一个任务对象
SumTask sumTask(numbers, size);
// 用 TBB 的 paral