---
title: kpccl_shm_win_alloc
description: "为指定kpccl comm的每个进程分配一块等长共享内存空间，可通过kpccl win访问。"
url: https://www.hikunpeng.com/document/detail/zh/hpchistory/hpckit/develop2400/KunoengHPCKit_developer_058.html
sourcePath: /source/zh/hpchistory/hpckit/develop2400/KunoengHPCKit_developer_058.html
indexId: a2721d675369651dd80b3299941b3b73a7b03a44693b05f855f08f73ed2dcd1473
---
# kpccl_shm_win_alloc

为指定kpccl comm的每个进程分配一块等长共享内存空间，可通过kpccl win访问。

#### 接口定义

int kpccl_shm_win_alloc(size_t size, kpccl_shm_comm_h comm, void **baseptr, kpccl_shm_win_h *win)


#### 环境变量

使用环境变量 KPCCL_SHM_TYPE 控制共享内存底层实现方式。

可选值：

- posix（默认）
- xpmem


#### 参数


**表1 参数定义**

| 参数名 | 类型 | 描述 | 输入/输出 |
| --- | --- | --- | --- |
| size | size\_t | 共享内存空间字节大小 | 输入 |
| comm | kpccl\_shm\_comm\_h | kpccl通信域 | 输入 |
| baseptr | void \*\* | 进程共享内存块的首地址 | 输出 |
| win | kpccl\_shm\_win\_h \* | 需要创建的window对象 | 输出 |


#### 返回值

- 成功：返回KPCCL_OK
- 失败：返回KPCCL_ERROR


#### 示例

```
#include <stdio.h>
#include <mpi.h>
#include "kpccl.h"
int oob_allgather_callback(const void *sendbuf, void *recvbuf, int size, void *group，kpccl_shm_datatype_t datatype)
{
switch (datatype) {
case KPCCL_SHM_DATATYPE_CHAR:
return MPI_Allgather(sendbuf, size, MPI_CHAR, recvbuf, size, MPI_CHAR, (MPI_Comm)group);
case KPCCL_SHM_DATATYPE_INT:
return MPI_Allgather(sendbuf, size, MPI_INT, recvbuf, size, MPI_INT, (MPI_Comm)group);
case KPCCL_SHM_DATATYPE_LONG:
return MPI_Allgather(sendbuf, size, MPI_LONG, recvbuf, size, MPI_LONG, (MPI_Comm)group);
case KPCCL_SHM_DATATYPE_FLOAT:
return MPI_Allgather(sendbuf, size, MPI_FLOAT, recvbuf, size, MPI_FLOAT, (MPI_Comm)group);
case KPCCL_SHM_DATATYPE_DOUBLE:
return MPI_Allgather(sendbuf, size, MPI_DOUBLE, recvbuf, size, MPI_DOUBLE, (MPI_Comm)group);
default:
kpccl_error("not support datatype");
return KPCCL_ERROR;
}
}
int
oob_barrier_callback(
void
*
group)
{
return MPI_Barrier((MPI_Comm)group);
}
int main()
{
int myid, numprocs;
int check = 1;
MPI_Comm comm = MPI_COMM_WORLD;
MPI_Comm_size(comm, &numprocs);
MPI_Comm_rank(comm, &myid);
kpccl_shm_oob_cb_t oob_cbs;
kpccl_shm_oob_cb_h oob_cbs_h = &oob_cbs;
oob_cbs_h->oob_allgather = oob_allgather_callback;
oob_cbs_h->oob_barrier = oob_barrier_callback;
kpccl_shm_comm_h kpccl_comm;
kpccl_shm_comm_create(numprocs, myid, myid, oob_cbs_h , (void *)comm, &kpccl_comm);
kpccl_shm_win_h win;
void *baseptr;
kpccl_shm_win_alloc
(256, kpccl_comm, &baseptr, &win);
MPI_Barrier(comm);
void *attach_address;
kpccl_shm_win_query(win, 0, &attach_address);
((int *)attach_address)[myid] = myid + 1;
MPI_Barrier(comm);
if (myid == 0) {
for (int i = 0; i < numprocs; i++) {
if (((int *)attach_address)[i] != I + 1) {
check = 0;
break;
}
}
if (check) {
printf("check success\n");
} else {
printf("check failed\n");
}
}
kpccl_shm_win_free(win);
kpccl_shm_comm_destroy(kpccl_comm);
}
```

运行结果如下。

```
check success
```

上述示例演示了创建、查询、清理一个kpccl win的流程。kpccl_shm_win_alloc函数创建一个kpccl win。
