简体   繁体   English

如何将 TypeScript 变量声明为 volatile?

[英]How do I declare a TypeScript variable as volatile?

I am working with the BBC Micro Bit and am creating an extension for Make Code in TypeScript.我正在与BBC Micro Bit 合作,并正在为 TypeScript 中的 Make Code 创建扩展。

I have the following event that gets triggered by a wheel encoder on my robot.我有以下事件由我的机器人上的车轮编码器触发。 Inside the event, I increment a couple of variables.在事件内部,我增加了几个变量。 In the Arduino language, I would declare such variables as "volatile" indicating that the variable could be changed by an interrupt, thus ensuring that I was working with the most recent value in the variable.在 Arduino 语言中,我将此类变量声明为“易失性”,表示该变量可以被中断更改,从而确保我使用的是变量中的最新值。

control.onEvent(EventBusSource.MICROBIT_ID_IO_P0, EventBusValue.MICROBIT_PIN_EVT_RISE, function () {
    _lTicks += 1;
    _lerrTicks += 1;
    if (_lTicks % _partialTurn == 0) {
        _lTicks = 0;
        _lTurns += .0625;
    }
})

Does TypeScript have an equivalent "volatile" keyword when declaring a variable?声明变量时,TypeScript 是否具有等效的“volatile”关键字? If so, how is it implemented?如果是这样,它是如何实施的?

Javascript has no volatile because JavaScript run-times are single threaded. Javascript 没有volatile因为 JavaScript 运行时是单线程的。 This means that there is is nothing to interrupt this code and no other code can change the state while the code runs.这意味着没有什么可以中断此代码,并且在代码运行时没有其他代码可以更改状态。

Generally if an event occurs during the execution of a piece of code, that event will be put in a queue and code associated with the event will only be executed once the current code stack is done running.通常,如果在执行一段代码期间发生了事件,则该事件将被放入队列中,并且与该事件关联的代码仅在当前代码堆栈运行完毕后才会执行。

Even things like WebWorkers which allow running multiple JS threads do not break this assumption.即使像WebWorkers这样允许运行多个 JS 线程的东西也不会打破这个假设。 They instead rely on message passing between the two threads without allowing for shared variables.相反,它们依赖于两个线程之间的消息传递,而不允许共享变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM