later icon indicating copy to clipboard operation
later copied to clipboard

Current loop at the idle R console can be something other than global loop

Open wch opened this issue 4 years ago • 0 comments

When current_loop() is called from the R console, it should always return the global loop, with ID 0. However, it's sometimes possible get it in a state where the current loop is not 0. I believe it has something to do with being interrupted at just the right time.

This is a reproducible example which uses some code from chromote. It's not truly minimal, but I haven't figured out a simpler way of making it happen.

First, install dev versions of later and chromote:

devtools::install_github(c('r-lib/later', 'rstudio/chromote'))

Then run this. After running the first block of code, press Ctrl-C or Esc as fast as you can, until "resolve" is printed.

library(later)
library(chromote)
{
  loop <- create_loop(autorun = F)
  p <- promise(function(resolve, reject) {
    later(
      function() {
        message("Current loop is ", current_loop()$id)
        message("resolve")
        resolve(TRUE)
      },
      2,
      loop = global_loop()
    )
  })
  print(current_loop())
  chromote:::synchronize(p, loop)
}
# Hit Esc or Ctrl-C a whole bunch of times now

current_loop()

Here's the output:

> library(later)
> library(chromote)
> {
+   loop <- create_loop(autorun = F)
+   p <- promise(function(resolve, reject) {
+     later(
+       function() {
+         message("Current loop is ", current_loop()$id)
+         message("resolve")
+         resolve(TRUE)
+       },
+       2,
+       loop = global_loop()
+     )
+   })
+   print(current_loop())
+   chromote:::synchronize(p, loop)
+ }
<event loop>
  id: 0Attempting to interrupt gracefully; press Esc/Ctrl+C to force interrupt

Current loop is 1
resolve
> current_loop()
<event loop>
  id: 1

Note that this doesn't work every time -- it may take a few tries before it does this. Also, even after the fix in #117 (which I thought might fix this), it still happens.

wch avatar Jan 11 '20 20:01 wch