Create multiple R instances on separate threads

Oct 6, 2015 at 12:33 AM
Hi,

Is it possible to either create multiple instances of the REngine or create multiple workspaces? I have several tasks which I want to run in parallel which call R to do some computation. They need to be sand boxed from each other as the use the same R variable names. When I try and call REngine.GetInstance() on multiple background threads it hangs i.e.
        static void Main(string[] args) {
            var tasks = new List<Task>();
            tasks.Add(Task.Run(() => { REngine.GetInstance(); Console.WriteLine("Instance 1 Created"); }));
            tasks.Add(Task.Run(() => { REngine.GetInstance(); Console.WriteLine("Instance 2 Created"); }));
            Task.WaitAll(tasks.ToArray());
            Console.WriteLine("Finished...");
            Console.ReadKey();
        }
Fails, seems to be some sort of deadlock in GetInstance as the Console.WriteLine is never reached. I'd appreciate any help on whether async is possible and if so what's the recomended approach?

Regards
Dave
Developer
Oct 9, 2015 at 9:13 PM
No, it is not. R itself is overwhelmingly not thread safe (at least the R project release one - I don't know about other new/commercial offerings), and in all but very specific cases will crash/deadlock/whatever. Nothing R.NET can do about.
Oct 10, 2015 at 2:31 AM
OK no problems, I created a static instance of REngine and have been locking on it to ensure only 1 thread accesses at a time. I was hoping that R would at least allow multiple workspaces but no worries.
Nov 16, 2015 at 11:01 AM
dwaterworth wrote:
OK no problems, I created a static instance of REngine and have been locking on it to ensure only 1 thread accesses at a time. I was hoping that R would at least allow multiple workspaces but no worries.
I guess we got the same answer, here I leave an explanation and an example for future reference: R.NET Multiple Instances
Nov 17, 2015 at 2:45 AM
Hi,

Yes I pretty much did the same thing
   public static class R
    {
        static R()
        {
            Engine = REngine.GetInstance();
        }

        private R() {}

        public static REngine Engine { get; protected set; }
    }
lock (R.Engine) {
    R.Engine.ClearGlobalEnvironment();
    R.Engine.Evaluate(@"library(reshape2)");

    // etc.
}