如题:Sendable 序列化?
问题描述:
@Sendable
export class Demo {
count:number = 0;
static demo:Demo = null;
static asyncLock: AsyncLock = new AsyncLock();
static async getInstace() {
return await Demo.asyncLock.lockAsync(()=>{
if (demo == null) {
demo = new Demo()
}
return demo;
})
}
async setCount(count: number) {
// 这里不用asyncLock.async的话,是不是就不会出现线程竞争?
// 我们的一个场景:网络库的全局拦截器中,不会访问类成员变量,也不希望产生线程竞争
await Demo.asyncLock.async(()=> {
this.count = count;
})
}
}
支持SendableClass序列化。对象分配在各自的虚拟机内存空间,不存在竞争访问,不同线程可以同时读写。
参考文档:https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/arkts-sendable-0000001820999729
共享模式后存在竞争,如果不出现竞争,就不需要加lock。