【HarmonyOS NEXT】鴻蒙多線程Sendable開發

非共享模塊在同一線程內只加載一次,在不同線程間會加載多次,單例類也會創建多次,導致數據不共享,在不同的線程內都會產生新的模塊對象

基礎概念

Sendable協議

Sendable協議定義了ArkTS的可共享對象體系及其規格約束。符合Sendable協議的數據(以下簡稱Sendable數據)可以在ArkTS并發實例間傳遞。

默認情況下,Sendable數據在ArkTS并發實例間(包括主線程、TaskPool&Worker工作線程)傳遞的行為是引用傳遞。同時,ArkTS支持Sendable數據在ArkTS并發實例間的拷貝傳遞。

當多個并發實例嘗試同時更新可變Sendable數據時,會發生數據競爭。ArkTS提供了異步鎖的機制來避免不同并發實例間的數據競爭。

示例:

import { taskpool, worker } from '@kit.ArkTS';@Sendable
class A {}let a: A = new A();@Concurrent
function foo(a: A) {}
let task: taskpool.Task = new taskpool.Task(foo, a)let w = new worker.ThreadWorker("entry/ets/workers/Worker.ets")// 1. TaskPool 共享傳輸實現方式
taskpool.execute(task).then(() => {})// 2. Worker 共享傳輸實現方式
w.postMessageWithSharedSendable(a)// 3. TaskPool 拷貝傳輸實現方式
task.setCloneList([a])
taskpool.execute(task).then(() => {})// 4. Worker 拷貝傳輸實現方式
w.postMessage(a)

Sendable class

Sendable class需同時滿足以下兩個規則:

  1. 當且僅當被標注了@Sendable裝飾器。
  2. 需滿足Sendable約束,詳情可查Sendable使用規則。

Sendable interface

Sendable interface需同時滿足以下兩個規則:

  1. 當且僅當是ISendable或者繼承了ISendable。
  2. 需滿足Sendable約束,詳情可查Sendable使用規則。

Sendable支持的數據類型

  • 所有的ArkTS基本數據類型:boolean, number, string, bigint, null, undefined。
  • ArkTS語言標準庫中定義的容器類型數據(須顯式引入@arkts.collections)。
  • ArkTS語言標準庫中定義的AsyncLock對象(須顯式引入@arkts.utils)。
  • 繼承了ISendable的interface。
  • 標注了@Sendable裝飾器的class。
  • 接入Sendable的系統對象類型(詳見Sendable系統對象)。
  • 元素均為Sendable類型的union type數據。

說明:

  • JS內置對象在并發實例間的傳遞遵循結構化克隆算法,語義為拷貝傳遞。因此JS內置對象的實例不是Sendable類型。

  • 對象字面量、數組字面量在并發實例間的傳遞遵循結構化克隆算法,語義為拷貝傳遞。因此,對象字面量和數組字面量不是Sendable類型。

  • ArkTS容器集與原生API行為差異具體參考行為差異匯總。

ISendable

在ArkTS語言基礎庫@arkts.lang中引入interface ISendable {},沒有任何必須的方法或屬性。ISendable是所有Sendable類型(除了null和undefined)的父類型。ISendable主要用在開發者自定義Sendable數據結構的場景中。類裝飾器@Sendable是implement ISendable的語法糖。

@Sendable裝飾器:聲明并校驗Sendable class

說明:

從API version 11開始,該裝飾器支持在ArkTS卡片中使用。

裝飾器說明

@Sendable類裝飾器說明
裝飾器參數無。
使用場景限制僅支持在Stage模型的工程中使用。僅支持在.ets文件中使用。
裝飾的類繼承關系限制Sendable class只能繼承Sendable class,普通Class不可以繼承Sendable class。
裝飾的對象內的屬性類型限制1. 支持string、number、boolean、bigint、null、undefined、Sendable class、collections.Array、collections.Map、collections.Set。
2. 禁止使用閉包變量。
3. 不支持#定義私有屬性,需用private。
4. 不支持計算屬性。
裝飾的對象內的屬性的其他限制成員屬性必須顯式初始化。成員屬性不能跟感嘆號。
裝飾的對象內的方法參數限制允許使用local變量、入參和通過import引入的變量。禁止使用閉包變量。
Sendable Class的限制不支持增加屬性、不支持刪除屬性、允許修改屬性,修改前后屬性的類型必須一致、不支持修改方法。
適用場景1. 在TaskPool或Worker中使用類方法。
2. 傳輸對象數據量較大的使用場景。

裝飾器使用示例

@Sendable
class SendableTestClass {desc: string = "sendable: this is SendableTestClass ";num: number = 5;printName() {console.info("sendable: SendableTestClass desc is: " + this.desc);}get getNum(): number {return this.num;}
}

Sendable使用規則

1. Sendable class只能繼承自Sendable class

說明:

這里的class不包括變量。Sendable class不能繼承自變量。

正例:

@Sendable
class A {constructor() {}
}@Sendable
class B extends A {constructor() {super()}
}

反例:

class A {constructor() {}
}@Sendable
class B extends A {constructor() {super()}
}

2. 非Sendable class只能繼承自非Sendable class

正例:

class A {constructor() {}
}class B extends A {constructor() {super()}
}

反例:

@Sendable
class A {constructor() {}
}class B extends A {constructor() {super()}
}

3. 非Sendable class只能實現非Sendable interface

正例:

interface I {};class B implements I {};

反例:

import { lang } from '@kit.ArkTS';type ISendable = lang.ISendable;interface I extends ISendable {};class B implements I {};

4. Sendable class/interface成員變量必須是Sendable支持的數據類型

正例:

@Sendable
class A {constructor() {}a: number = 0;
}

反例:

@Sendable
class A {constructor() {}b: Array<number> = [1, 2, 3] // 需使用collections.Array
}

5. Sendable class/interface的成員變量不支持使用!斷言

正例:

@Sendable
class A {constructor() {}a: number = 0;
}

反例:

@Sendable
class A {constructor() {}a!: number;
}

6. Sendable class/interface的成員變量不支持使用計算屬性名

正例:

@Sendable
class A {num1: number = 1;num2: number = 2;add(): number {return this.num1 + this.num2;}
}

反例:

enum B {b1 = "bbb"
}
@Sendable
class A {["aaa"]: number = 1; // ["aaa"] is allowed in other classes in ets files[B.b1]: number = 2; // [B.b1] is allowed in other classes in ets files
}

7. 泛型類中的Sendable class,collections.Array,collections.Map,collections.Set的模板類型必須是Sendable類型

正例:

import { collections } from '@kit.ArkTS';try {let arr1: collections.Array<number> = new collections.Array<number>();let num: number = 1;arr1.push(num)
} catch (e) {console.error(`taskpool execute: Code: ${e.code}, message: ${e.message}`);
}

反例:

import { collections } from '@kit.ArkTS';try {let arr1: collections.Array<Array<number>> = new collections.Array<Array<number>>();let arr2: Array<number> = new Array<number>()arr2.push(1)arr1.push(arr2)
} catch (e) {console.error(`taskpool execute: Code: ${e.code}, message: ${e.message}`);
}

8. Sendable class的內部不允許使用當前模塊內上下文環境中定義的變量

由于Sendable對象在不同并發實例間的上下文環境不同,如果直接訪問會有非預期行為。不支持Sendable對象使用當前模塊內上下文環境中定義的變量,如果違反,編譯階段會報錯。

說明:

從API version 12開始,sendable class的內部支持使用top level的sendable class對象。

正例:

import { lang } from '@kit.ArkTS';type ISendable = lang.ISendable;interface I extends ISendable {}@Sendable
class B implements I {static o: number = 1;static bar(): B {return new B();}
}@Sendable
class C {v: I = new B();u: number = B.o;foo() {return B.bar();}
}

反例:

import { lang } from '@kit.ArkTS';type ISendable = lang.ISendable;interface I extends ISendable {}@Sendable
class B implements I {}function bar(): B {return new B();
}let b = new B();{@Sendableclass A implements I {}@Sendableclass C {u: I = bar(); // bar不是sendable class對象,編譯報錯v: I = new A(); // A不是定義在top level中,編譯報錯foo() {return b; // b不是sendable class對象,而是sendable class的實例,編譯報錯}}
}

9. Sendable class中不能使用除了@Sendable的其它裝飾器

如果類裝飾器定義在ts文件中,產生修改類的布局的行為,那么會造成運行時的錯誤。

正例:

@Sendable
class A {num: number = 1;
}

反例:

@Sendable
@Observed
class C {num: number = 1;
}

10. 不能使用對象字面量/數組字面量初始化Sendable類型

Sendable數據類型只能通過Sendable類型的new表達式創建。

正例:

import { collections } from '@kit.ArkTS';let arr1: collections.Array<number> = new collections.Array<number>(1, 2, 3); // 是Sendable類型

反例:

import { collections } from '@kit.ArkTS';let arr2: collections.Array<number> = [1, 2, 3]; // 不是Sendable類型,編譯報錯
let arr3: number[] = [1, 2, 3]; // 不是Sendable類型,正例,不報錯
let arr4: number[] = new collections.Array<number>(1, 2, 3); // 編譯報錯

11. 非Sendable類型不可以as成Sendable類型

說明:

Sendable類型在不違反Sendable規則的前提下需要和非Sendable類型行為兼容,因此Sendable類型可以as成非Sendable類型。

正例:

class A {state: number = 0;
}@Sendable
class SendableA {state: number = 0;
}let a1: A = new SendableA() as A;

反例:

class A {state: number = 0;
}@Sendable
class SendableA {state: number = 0;
}let a2: SendableA = new A() as SendableA;

與TS/JS交互的規則

ArkTS通用規則(目前只針對Sendable對象)

規則
Sendable對象傳入TS/JS的接口中,禁止操作其對象布局(增、刪屬性,改變屬性類型)。
Sendable對象設置到TS/JS的對象上,TS中獲取到這個Sendable對象后,禁止操作其對象布局(增、刪屬性,改變屬性類型)。
Sendable對象放入TS/JS的容器中,TS中獲取到這個Sendable對象后,禁止操作其對象布局(增、刪屬性,改變屬性類型)。

說明:

此處改變屬性類型不包括Sendable對象類型的改變,比如從Sendable class A 變為Sendable class B。

NAPI規則(目前只針對Sendable對象)

規則
禁止刪除屬性,不能使用的接口有:napi_delete_property。
禁止新增屬性,不能使用的接口有:napi_set_property、napi_set_named_property、napi_define_properties。
禁止修改屬性類型,不能使用的接口有:napi_set_property、napi_set_named_property、napi_define_properties。
不支持Symbol相關接口和類型,不能使用的接口有:napi_create_symbol、napi_is_symbol_object、napi_symbol。

使用場景

Sendable對象可以在不同并發實例間通過引用傳遞。通過引用傳遞方式傳輸對象相比序列化方式更加高效,同時不丟失class上攜帶的成員方法,因此,Sendable主要可以解決兩個場景的問題: 1.?跨并發實例傳輸大數據(例如可能達到100KB以上) 2.?跨并發實例傳遞帶方法的class實例對象

跨并發實例傳輸大數據場景開發指導

由于跨并發實例序列化的開銷隨著數據量線性增長,因此當傳輸數據量較大時(100KB數據大約1ms傳輸耗時),跨并發實例的拷貝開銷大,影響并行化的性能。引用傳遞方式傳輸對象可提升性能。

示例:

// index.ets
import { taskpool } from '@kit.ArkTS';
import { testTypeA, testTypeB, Test } from './sendable'// 在并發函數中模擬數據處理
@Concurrent
async function taskFunc(obj: Test) {console.info("test task res1 is: " + obj.data1.name + " res2 is: " + obj.data2.name);
}async function test() {// 使用taskpool傳遞數據let a: testTypeA = new testTypeA("testTypeA");let b: testTypeB = new testTypeB("testTypeB");let obj: Test = new Test(a, b);let task: taskpool.Task = new taskpool.Task(taskFunc, obj);await taskpool.execute(task);
}test();
// sendable.ets
// 將數據量較大的數據在Sendable class中組裝
@Sendable
export class testTypeA {name: string = "A";constructor(name: string) {this.name = name;}
}@Sendable
export class testTypeB {name: string = "B";constructor(name: string) {this.name = name;}
}@Sendable
export class Test {data1: testTypeA;data2: testTypeB;constructor(arg1: testTypeA, arg2: testTypeB) {this.data1 = arg1;this.data2 = arg2;}
}

跨并發實例傳遞帶方法的class實例對象

由于序列化傳輸實例對象時會丟失方法,在必須調用實例方法的場景中,需使用引用傳遞方式進行開發。在數據處理過程中有需要解析的數據,可使用ASON工具進行數據解析。

示例:

// Index.ets
import { taskpool, ArkTSUtils } from '@kit.ArkTS'
import { SendableTestClass, ISendable } from './sendable'// 在并發函數中模擬數據處理
@Concurrent
async function taskFunc(sendableObj: SendableTestClass) {console.info("SendableTestClass: name is: " + sendableObj.printName() + ", age is: " + sendableObj.printAge() + ", sex is: " + sendableObj.printSex());sendableObj.setAge(28);console.info("SendableTestClass: age is: " + sendableObj.printAge());// 解析sendableObj.arr數據生成JSON字符串let str = ArkTSUtils.ASON.stringify(sendableObj.arr);console.info("SendableTestClass: str is: " + str);// 解析該數據并生成ISendable數據let jsonStr = '{"name": "Alexa", "age": 23, "sex": "female"}';let obj = ArkTSUtils.ASON.parse(jsonStr) as ISendable;console.info("SendableTestClass: type is: " + typeof obj);console.info("SendableTestClass: name is: " + (obj as object)?.["name"]); // 輸出: 'Alexa'console.info("SendableTestClass: age is: " + (obj as object)?.["age"]); // 輸出: 23console.info("SendableTestClass: sex is: " + (obj as object)?.["sex"]); // 輸出: 'female'
}
async function test() {// 使用taskpool傳遞數據let obj: SendableTestClass = new SendableTestClass();let task: taskpool.Task = new taskpool.Task(taskFunc, obj);await taskpool.execute(task);
}test();
// sendable.ets
// 定義模擬類Test,模仿開發過程中需傳遞帶方法的class
import { lang, collections  } from '@kit.ArkTS'export type ISendable = lang.ISendable;@Sendable
export class SendableTestClass {name: string = 'John';age: number = 20;sex: string = "man";arr: collections.Array<number> = new collections.Array<number>(1, 2, 3);constructor() {}setAge(age: number) : void {this.age = age;}printName(): string {return this.name;}printAge(): number {return this.age;}printSex(): string {return this.sex;}
}

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/web/38304.shtml
繁體地址,請注明出處:http://hk.pswp.cn/web/38304.shtml
英文地址,請注明出處:http://en.pswp.cn/web/38304.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

STM32mp157aaa按鍵中斷實驗

效果圖&#xff1a; 源碼&#xff1a; #include "key.h" void hal_key1_rcc_gpio_init() {// 使能GPIOF組RCC->MP_AHB4ENSETR | (0x1 << 5);// 設置引腳位輸入模式GPIOF->MODER & (~(0X3 << 18));GPIOF->MODER & (~(0X3 << 16))…

[C++11] 退出清理函數(quick_exit at_quick_exit)

說明&#xff1a;在C11中&#xff0c;quick_exit和at_quick_exit是新增的快速退出功能&#xff0c;用于在程序終止時提供一種快速清理資源的方式。 quick_exit std::quick_exit函數允許程序快速退出&#xff0c;并且可以傳遞一個退出狀態碼給操作系統。與std::exit相比&#…

[今日一水]論壇該如何選擇

想要搭建一個論壇其實選擇是很多的&#xff0c;就比如國內的dz&#xff0c;國外的xenforo和flarum&#xff0c;具體還是根據的面向的用戶和需求來&#xff0c;就比如flarum它的界面肯定是三個論壇里最現代化的&#xff0c;但是xenforo社區生態很強&#xff0c;而dz對于國內用戶…

VMware創建新虛擬機教程(保姆級別)

&#x1f4e2; 續上一篇 最新超詳細VMware虛擬機安裝完整教程-CSDN博客 &#xff0c;本章將詳細講解VMware創建虛擬機。 一、創建新的虛擬機 點擊【創建新的虛擬機】&#xff01; 點擊【自定義&#xff08;高級&#xff09;】> 下一步&#xff01; > 默認下一步&#x…

耐克:老大的煩惱

股價暴跌20%&#xff0c;老大最近比較煩。 今天說說全球&#xff08;最&#xff09;大運動品牌——耐克。 最近耐克發布2023-2024財年業績&#xff08;截止于2024.5.31&#xff09;&#xff0c;還是爆賺幾百億美元&#xff0c;還是行業第一&#xff0c;但業績不及預期&#xf…

Redis為什么設計多個數據庫

?關于Redis的知識前面已經介紹過很多了,但有個點沒有講,那就是一個Redis的實例并不是只有一個數據庫,一般情況下,默認是Databases 0。 一 內部結構 設計如下: Redis 的源碼中定義了 redisDb 結構體來表示單個數據庫。這個結構有若干重要字段,比如: dict:該字段存儲了…

backbone是什么?

在深度學習中&#xff0c;特別是計算機視覺領域&#xff0c;"backbone"&#xff08;骨干網絡&#xff09;是指用于提取特征的基礎網絡。它通常是卷積神經網絡&#xff08;CNN&#xff09;&#xff0c;其任務是從輸入圖像中提取高層次特征&#xff0c;這些特征然后被用…

【第12章】MyBatis-Plus條件構造器(下)

文章目錄 前言一、使用 TypeHandler二、使用提示三、Wrappers四、線程安全性五、使用 Wrapper 自定義 SQL1.注意事項2.示例3. 使用方法 總結 前言 本章繼續上章條件構造器相關內容。 一、使用 TypeHandler 在 wrapper 中使用 typeHandler 需要特殊處理利用 formatSqlMaybeWit…

scikit-learn教程

scikit-learn&#xff08;通常簡稱為sklearn&#xff09;是Python中最受歡迎的機器學習庫之一&#xff0c;它提供了各種監督和非監督學習算法的實現。下面是一個基本的教程&#xff0c;涵蓋如何使用sklearn進行數據預處理、模型訓練和評估。 1. 安裝和導入包 首先確保安裝了…

【漏洞復現】D-Link NAS 未授權RCE漏洞(CVE-2024-3273)

0x01 產品簡介 D-Link 網絡存儲 (NAS)是中國友訊&#xff08;D-link&#xff09;公司的一款統一服務路由器。 0x02 漏洞概述 D-Link NAS nas_sharing.cgi接口存在命令執行漏洞&#xff0c;該漏洞存在于“/cgi-bin/nas_sharing.cgi”腳本中&#xff0c;影響其 HTTP GET 請求處…

類和對象-友元-全局函數做友元

全局函數做友元 #include<iostream> using namespace std;class Building {//goodGay全局函數是Building好朋友&#xff0c;可以訪問Building的私有成員 friend void goodGay(Building *building); public:Building(){m_SittingRoom "客廳";m_BedRoom &qu…

MyBatis學習筆記-數據脫敏

如果項目需要對一些特殊、敏感的數據進行脫敏處理。根據實際的需求可以考慮在讀寫的過程中分別做脫敏操作。 一、寫過程參數脫敏 主要是使用mybatis框架提供的Interceptor實現。需要考慮不同類型的參數解析處理方式不同。 @Slf4j @AllArgsConstructor @Intercepts({@Signatu…

【vuejs】vue-router 之 addRoute 動態路由的應用總結

1. Vue Router 概述 Vue Router 是 Vue.js 官方的路由管理器&#xff0c;用于構建單頁面應用。它與 Vue.js 深度集成&#xff0c;讓開發者能夠輕松地構建具有復雜用戶界面的單頁面應用。Vue Router 允許你定義不同的路由&#xff0c;并通過 router-view 組件在應用中顯示匹配的…

【CSS】如何實現分欄布局

在CSS分欄布局中&#xff0c;設置寬度和樣式是一個基本且重要的步驟。這可以通過直接應用樣式到列元素&#xff08;通常是div元素&#xff09;上來實現。以下是一些常用的方法來設置分欄布局的寬度和樣式&#xff1a; 1. 使用百分比寬度 使用百分比寬度可以使列的大小相對于其…

MyBatis學習筆記-參數轉義處理

查詢參數中如果有傳入%的情況,數據會被全量返回。類似的可能還會有一些特殊符號的情況存在。這個時候可能需要在查詢數據的時候進行參數轉義處理。一般情況可能會考慮選擇下面的兩種方式處理。 一、基于Filter處理 主要通過實現Filter接口,自定義HttpServletRequestWrapper…

Stable Diffusion秋葉AnimateDiff與TemporalKit插件沖突解決

文章目錄 Stable Diffusion秋葉AnimateDiff與TemporalKit插件沖突解決描述錯誤描述&#xff1a;找不到模塊imageio.v3解決&#xff1a;參考地址 其他文章推薦&#xff1a;專欄 &#xff1a; 人工智能基礎知識點專欄&#xff1a;大語言模型LLM Stable Diffusion秋葉AnimateDiff與…

Java 漢諾塔問題 詳細分析

漢諾塔 漢諾塔&#xff08;Tower of Hanoi&#xff09;&#xff0c;又稱河內塔&#xff0c;是一個源于印度古老傳說的益智玩具。大梵天創造世界的時候做了三根金剛石柱子&#xff0c;在一根柱子上從下往上按照大小順序摞著64片黃金圓盤。大梵天命令婆羅門把圓盤從下面開始按大小…

vulnhub靶場ai-web 2.0

1 信息收集 1.1 主機發現 arp-scan -l 主機地址為192.168.1.4 1.2 服務端口掃描 nmap -sS -sV -A -T5 -p- 192.168.1.4 開放22&#xff0c;80端口 2 訪問服務 2.1 80端口訪問 http://192.168.1.4:80/ 先嘗試admin等其他常見用戶名登錄無果 然后點擊signup發現這是一個注…

prescan軟件中導入路徑文件txt/lpx

由于博主收到的是lpx格式的路徑文件&#xff0c;因此&#xff0c;第一步 1.記事本打開 ctrla 全選 ctrlc 復制 2.新建一個excel 鼠標定位到第一行第一列的格子 ctrlv 復制 3.數據欄“分列”功能 4. (0.1遞增的數列&#xff0c;緯度&#xff0c;經度&#xff0c;高程) 導入…

python——面向對象小練習士兵突擊與信息管理系統

士兵突擊 需求 1. 士兵 許三多 有一把 AK47 2. 士兵 可以 開火 3. 槍 能夠 發射 子彈 4. 槍 裝填 裝填子彈 —— 增加子彈數量 # 士兵突擊 # 需求 # 1. 士兵 許三多 有一把 AK47 # 2. 士兵 可以 開火 # 3. 槍 能夠 發射 子彈 # 4. 槍 裝填 裝填子彈 —— 增加子彈數量 cl…