Currently, calls into R via rpy2 are *mostly* protected by the Python
global interpreter lock. That means that calling rpy2 functions from
different threads *almost* just works (even though R is not itself
re-entrant). However, it happens from time to time that R calls back
into Python (most commonly, via the console print callback), and then
Python might release the GIL, so you get:

Thread 1:
  acquire GIL
    call R
      call Python
        release GIL
Thread 2:
        acquire GIL
          call R
            blow up

Oh well. The only solution is to add a GIL-alike lock for R. (Well,
that or never call into R from different threads, but that is very
irksome. Or do locking manually, but that's even worse.) So here's a
tedious patch does that (and also cleans up the "is R initialized
yet?" checking that is currently copy-pasted all over the code). It
uses Python threading API, so it should work anywhere that Python does
(though testing is always good).

With the patch applied, all current tests continue to pass, and the
following code works without error (without the patch it crashes
whenever a reasonable amount of text is printed):

_r_polling_thread = None
def process_forever():
  while True:
    time.sleep(1. / 100)
    ri.process_revents()
def interactive():
  global _r_polling_thread
  if _r_polling_thread is None:
    _r_polling_thread = threading.Thread(target=process_forever)
    _r_polling_thread.setDaemon(True)
    _r_polling_thread.start()

Patch is available at:
  https://bitbucket.org/njs/rpy2-pending-patches/src/tip/add_global_r_lock
though it might want
  https://bitbucket.org/njs/rpy2-pending-patches/src/tip/detabify-apply-me-first
to apply cleanly.

-- Nathaniel

------------------------------------------------------------------------------
Create and Deploy Rich Internet Apps outside the browser with Adobe(R)AIR(TM)
software. With Adobe AIR, Ajax developers can use existing skills and code to
build responsive, highly engaging applications that combine the power of local
resources and data with the reach of the web. Download the Adobe AIR SDK and
Ajax docs to start building applications today-http://p.sf.net/sfu/adobe-com
_______________________________________________
rpy-list mailing list
rpy-list@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/rpy-list

Reply via email to