gpane
gpane

Reputation: 41

Run two Lua-functions from Qt/C++-App parallel

I have a Qt-Application written in C++. It's a generic Tool for testing hardware. The specific tests are defined in a lua-script.

In my script i have a function called 'RunTests()' which is called in a QThread in the Qt-Application. I put it into a QThread in order to prevent the script from freezing my application. Now there's another function in the lua script, called 'Interrupt()' which should be called sometimes by the Qt-Application during the tests. So now everytime I call this function 'Interrupt()' with lua_getglobal() my Qt-Application crashes.

How can I run those 2 Lua functions at the same time or how can I interrupt 'RunTests()' to call 'Interrupt()' and then move back to 'RunTests()'?

Upvotes: 3

Views: 300

Answers (3)

gpane
gpane

Reputation: 41

I now solved the problem by using coroutines.

So when my two functions are:

function DataHandler(data)
    buffer = buffer .. data
    ...
end

function Tests()
    ...
end

I added the following lines of code:

co_DataHandler = coroutine.create(DataHandler)
co_Tests = coroutine.create(Tests)

With this I am able to run DataHandler() within the same QThread while Tests() is doing some other stuff.

Upvotes: 0

Ulrich Eckhardt
Ulrich Eckhardt

Reputation: 17415

Your question boils down to "How can I interrupt a thread?". This is a common question and the answer is usually that you can't, but that there are other ways. The simple reason why you can't is that a thread might be in the middle of some operation that modifies global state, like a heap allocation. If you killed it in the middle, it would leave data structures in a temporarily invalid state and leave mutexes locked.

Two approaches come to mind that might work for you:

  • You could ask the thread to exit. If your thread regularly checked a flag (that could be a variable in a C++ function exported to Lua) and then reacted accordingly, you could set the flag and wait for the thread to finish.
  • Another common approach is that you don't use threads but processes instead. Other than threads, a process can be terminated and the OS guarantees proper cleanup. Downside is that processes don't share state, so you would have to set up some kind of IPC.
  • A third approach might also work, but it depends on the system you are on. On POSIX systems, you could use signals to trigger thread termination. However, for that, it must be properly supported by the code. If Lua doesn't support it, you are out of luck and on other OSs probably too.

Upvotes: 1

lhf
lhf

Reputation: 72312

You cannot run concurrent scripts in the same Lua state.

You can run concurrent scripts in separate Lua states.

Upvotes: 2

Related Questions