Wait for Asynchronous Event in Lua

谁说我不能喝 提交于 2019-12-24 22:47:32

问题


I have a library in Lua that creates and parses data packets for a protocol. When I send a packet out, I'm expecting a reply back from the destination that is then parsed into a table. I'm trying to write a wrapper around this library so that I can make a function call like the following: result = SendUnicast(dest,packetData) and have the parsed response table returned to result.

My problem is two fold: 1) The incoming message comes in asynchronously and on a different thread than the executing script and 2) the next packet I receive isn't necessarily the response for my request, I have to parse the incoming packet and match a sequence id.

The program flow currently looks something like:

[C# UI Thread]

  • Button Click
  • Run Lua Script
    • Call SendUnicast
    • Wait For Response

[C# Data Thread]

  • Incoming Message
    • Pass message to Lua parser function
    • if sequence matches waiting command, store parsed table, resume blocked

[C# UI Thread]

  • Lua scipt returns parsed table

I can't seem to find a good method for blocking the currently executing script (in the UIThread). Creating a coroutine to be called when the message is parsed and then while coroutine.status(co) ~= "dead" seems to kill my lua interpreter.

EDIT

I'm marking BMitch's answer as accepted because it is the correct way to handle this issue. I will warn you, however, that LuaInterface does not support coroutines and I had to add support for them to the C# code myself.


回答1:


In the UI thread, run:

while ((status=lua_resume(L_coroutine, 0)) == LUA_YIELD) {
  semaphore_wait(); /* whatever the appropriate C# call is */
}

"Wait for response" should look something like:

while not results[my_result] do
  coroutine.yield()
end

The "incoming message" function should look like the following in Lua:

results[cur_result]=parsed_message

And finally back in C# for the "incoming message", call the appropriate semaphore_post() function.

Sorry if my C# looks terrible, I'm a C programmer on Linux, so I tried to keep that side generic.



来源:https://stackoverflow.com/questions/6683928/wait-for-asynchronous-event-in-lua

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!