1

Is there a way to make LuaInterface work in a multithreaded environment?

I have a multithreaded c# (.Net 4) assembly that uses LuaInterface to process data from a native application. Each thread has its own instance of the Lua interpreter. I use Lua.GetFunction() to retrieve a function from a script and call that function periodically. I pass a Dictionary to the function to process. This works fine with one thread. But when I use two threads it crashes the entire app and I see errors like the following in visual studio:

The thread 'Win32 Thread' (0xa78) has exited with code -1073740791 (0xc0000409).

If I change the script to do something trivial where it does not utilize the Dictionary I pass to it then it also works fine with multiple threads.

Am I going to have to give each interpreter its own process or AppDomain to make this work?

Galen
  • 499
  • 5
  • 14
  • Some code would help understand your problem better. – kikito Nov 15 '11 at 22:06
  • I'm working on a simplified project that demonstrates the problem. The problem with it is that it works! I'll have to compare it with my code at work tomorrow. I'll post some code as soon as possible. – Galen Nov 16 '11 at 02:08

3 Answers3

1

If you are trying to call the same Dictionary object from two different threads, then you have a data race. It doesn't matter if it's doing it because a Lua script said so or because C# code tried to do it. It's still a race condition. And if that Dictionary is not thread-safe, badness can result.

So you either need to provide thread-safe accessors to this object, or you need to not access the same object from two threads. This doesn't really have anything to do with Lua; it's just basic multithreading.

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
1

LuaInterface is not thread safe. From what I have read Lua itself appears to support multithreading (see Lua Lanes). However, LuaInterface(v2.0.3.7) still has some issues to work out before it is thread safe. Putting separate instances of the Lua interpreter in their own thread does not overcome these issues.

Galen
  • 499
  • 5
  • 14
0

What is the script doing with the dictionary? This is relevant since the dictionary class is not thread-safe.

Say, if the dictionary was changed in one thread while another thread enumerates it, that thread will crash.

Peter Lillevold
  • 33,668
  • 7
  • 97
  • 131
  • It is reading values from the dictionary. Each thread owns its own dictionary that it is passing to the script. So I don't believe that is the problem. The only reason I was using a dictionary was because I was using a LuaTable and I thought, at one point, it might have been part of the problem. I'll post some code tomorrow after I do some more investigating. – Galen Nov 16 '11 at 02:26