Galen
Galen

Reputation: 499

LuaInterface multi-threading crash

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?

Upvotes: 1

Views: 664

Answers (3)

Galen
Galen

Reputation: 499

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.

Upvotes: 1

Nicol Bolas
Nicol Bolas

Reputation: 473322

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.

Upvotes: 1

Peter Lillevold
Peter Lillevold

Reputation: 33920

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.

Upvotes: 0

Related Questions