---
title: ParallelFor
description: "并行化函数："
url: https://www.hikunpeng.com/document/detail/zh/kunpengboostkithistory/2300/accel/kunpengaccel_hmpp_06_0042.html
sourcePath: /source/zh/kunpengboostkithistory/2300/accel/kunpengaccel_hmpp_06_0042.html
indexId: 17a56b24b2092256344fa65f9d6755c91de9bdb41d63c129d2b514fa20f455ee75
---
# ParallelFor

并行化函数：

HmppResult HMPP_ParallelFor (int32_t numTasks, void *arg, function func);

可将要执行的多个任务封装在HmppResult(*function)(int32_t i, void *arg)内传入，使用方式见示例。


#### 参数

| 参数名 | 描述 | 取值范围 | 输入/输出 |
| --- | --- | --- | --- |
| numTasks | 任务数。 | 大于0（小于0不会报异常，可以认为就是一个任务都不创建）。 | 输入 |
| arg | 地址，指向func函数的参数值。 | 非空 | 输入 |
| func | 要执行函数（即任务）的函数指针。 | 非空 | 输入 |


#### 返回值

- 成功：返回HMPP_STS_NO_ERR。
- 失败：返回错误码。


#### 错误码

| 错误码 | 描述 |
| --- | --- |
| HMPP\_STS\_NULL\_PTR\_ERR | arg或func指针为空指针。 |


开启的多线程中也会返回错误码，该错误码在自定义函数中设定，由调用者决定。


#### 示例

```
#define LEN 20
void  ParallelFor_Example()
{
typedef struct {
int32_t val[LEN];
int32_t rangeLen;
}Arg;
// 此函数实现的功能：对数组某段区间的数取绝对值
auto func = [] (int32_t i, void *arg) -> HmppResult {
Arg *args = (Arg *)arg;
int32_t st = i * args->rangeLen;
int32_t ed = st + args->rangeLen;
for (int32_t k = st; k < ed; ++k) {
args->val[k] = abs(args->val[k]);
}
return HMPP_STS_NO_ERR;
};
Arg arg;
arg.rangeLen = 5;
for (int32_t i = 0; i < LEN; ++i) {
arg.val[i] = -(i + 1);
}
HmppResult result = HMPP_ParallelFor(LEN / arg.rangeLen, (void*)&arg, func);
for (int32_t i = 0; i < LEN; ++i) {
printf("%d\n", arg.val[i]);
}
}
```

运行结果：

```
```
