Angular 4 中是否可能存在竞争条件
Are race conditions possible in Angular 4
我的 Angular 4 服务:
@Injectable()
export class MyService {
private myArray: string[] = [];
constructor() { }
private calculate(result): void {
myArray.length = 0;
// Do some calculations and add results in myArray
}
public invokeCallBack(callBack: Function) {
// the function callBack returns an observable
// Rest calls are done in the callBack function
callBack().subscribe(
(result) => {
// Rest call is finished
this.calculate(result);
}
);
}
}
其他组件多次调用invokeCallBack(callBack)
如果同时完成 2 个(或更多)rest 调用会怎样?
1) this.calculate(result) 方法会被同时调用2次吗?如果是这种情况,则 myArray 可能具有不一致的状态,因为 2 个计算同时发生(=> 竞争条件)。这个问题怎么解决?
2) 还是 this.calculate(result) 总是被称为同步?如果是这种情况,一次只能进行一次计算,因此 myArray 始终(保证)处于一致状态。
假设 calculate
中没有异步代码,该方法将始终 运行 完成,然后再次调用。
不可能同时从 calculate
到 运行 中的 2 个单独的 "instances"。
这是因为 JavaScript(在浏览器中)is single-threaded。
我的 Angular 4 服务:
@Injectable()
export class MyService {
private myArray: string[] = [];
constructor() { }
private calculate(result): void {
myArray.length = 0;
// Do some calculations and add results in myArray
}
public invokeCallBack(callBack: Function) {
// the function callBack returns an observable
// Rest calls are done in the callBack function
callBack().subscribe(
(result) => {
// Rest call is finished
this.calculate(result);
}
);
}
}
其他组件多次调用invokeCallBack(callBack)
如果同时完成 2 个(或更多)rest 调用会怎样?
1) this.calculate(result) 方法会被同时调用2次吗?如果是这种情况,则 myArray 可能具有不一致的状态,因为 2 个计算同时发生(=> 竞争条件)。这个问题怎么解决?
2) 还是 this.calculate(result) 总是被称为同步?如果是这种情况,一次只能进行一次计算,因此 myArray 始终(保证)处于一致状态。
假设 calculate
中没有异步代码,该方法将始终 运行 完成,然后再次调用。
不可能同时从 calculate
到 运行 中的 2 个单独的 "instances"。
这是因为 JavaScript(在浏览器中)is single-threaded。