• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# GPU/CPU内存访问同步操作开发指南 (C/C++)
2<!--Kit: ArkGraphics 2D-->
3<!--Subsystem: Graphics-->
4<!--Owner: @Felix-fangyang; @li_hui180; @dingpy-->
5<!--Designer: @conan13234-->
6<!--Tester: @nobuggers-->
7<!--Adviser: @ge-yafang-->
8## 场景介绍
9
10NativeFence是提供**同步管理fenceFd**的模块。开发者可以通过`NativeFence`接口实现对fenceFd阻塞指定时间、永久阻塞、关闭和检查fenceFd是否有效等操作。
11
12## 接口说明
13
14| 接口名 | 描述 |
15| -------- | -------- |
16| OH_NativeFence_IsValid (int fenceFd) | 检查fenceFd是否有效。 |
17| OH_NativeFence_Wait (int fenceFd, uint32_t timeout) | 阻塞传入的fenceFd,最大阻塞时间由超时参数决定。 |
18| OH_NativeFence_WaitForever (int fenceFd) | 永久阻塞传入的fenceFd。 |
19| OH_NativeFence_Close (int fenceFd) | 关闭fenceFd。 |
20
21详细的接口说明请参考[NativeFence](../reference/apis-arkgraphics2d/capi-nativefence.md)。
22
23## 开发步骤
24
25以下步骤描述了如何使用`NativeFence`提供的Native API接口。
26
27**添加动态链接库**
28
29CMakeLists.txt中添加以下lib。
30```txt
31libnative_fence.so
32```
33
34**头文件**
35```c++
36#include <native_fence/native_fence.h>
37#include <cstring>
38#include <iostream>
39#include <linux/sync_file.h>
40#include <signal.h>
41#include <sys/signalfd.h>
42#include <unistd.h>
43```
441. **通过signalfd创建fenceFd**。
45    ```c++
46    sigset_t mask;
47    sigemptyset(&mask);
48    sigprocmask(SIG_BLOCK, &mask, NULL);
49
50    int fenceFd = signalfd(-1, &mask, 0);
51    ```
52
532. **判断传入的fenceFd是否合法**。
54    ```c++
55    // 检查fenceFd是否有效
56    bool isValid = OH_NativeFence_IsValid(fenceFd);
57    if (!isValid) {
58        std::cout << "fenceFd is invalid" << std::endl;
59    }
60    ```
61
623. **调用OH_NativeFence_Wait阻塞接口**。
63    ```c++
64    constexpr uint32_t TIMEOUT_MS = 5000;
65    bool resultWait = OH_NativeFence_Wait(fenceFd, TIMEOUT_MS);
66    if (!resultWait) {
67        std::cout << "OH_NativeFence_Wait Failed" << std::endl;
68    }
69    ```
70
714. **调用OH_NativeFence_WaitForever阻塞接口**。
72    ```c++
73    bool resultWaitForever = OH_NativeFence_WaitForever(fenceFd);
74    if (!resultWaitForever) {
75        std::cout << "OH_NativeFence_WaitForever Failed" << std::endl;
76    }
77    ```
78
795. **GPU或CPU进行信号触发signal,通知fenceFd解除阻塞**。
80
816. **关闭fenceFd**。
82    ```c++
83    OH_NativeFence_Close(fenceFd);
84    ```