Yielding a thread from another thread (lua) - lua

I am trying to create a sleep function for Lua, since my Lua-Scripts all run in a different thread/environment I wanted to yield their thread and restart from the main thread when the given amount of time elapsed, the main thread is in Java and the time elapsing is done with a loop.
Now this isn't really hard or something but I am trying to use Lua's own coroutines/threads so I don't have to create my own thread structure but (my Lua knowledge isn't top-notch) I don't know how I can yield a thread from outside of the thread.
Is it possible to yield a thread from the main thread?
Edit Nevermind, I just figured it out. I did a getfenv and used the coroutine.yield of the script it's own environment.

I used the script it's coroutine.yield function. Pretty easy looking back at it

Related

Trying to run two loops at the same time Minecraft ComputerCrafft

This is my code
https://pastebin.com/fnZreFKA
I have tried all the coroutine options, I have print statements at the start of each of the two functions, it prints, but it doesn't do anything in the loop
coroutine.wrap(constantWork)()
coroutine.wrap(lookForKeys)()
The loops start after line 170
Because they are not detached threads, they are green synchronous threads, only one of them will run the code at the time.
To simulate multitasking you forgot to use yield. coroutine.yield pauses the thread and runs the next code after you called the coroutine. You can resume the coroutine later on by calling wrapped coroutine again or using coroutine.resume if you created it using coroutine.create.
Read the documentation here: https://www.lua.org/pil/9.html
coroutine.wrap creates a new coroutine based on the function you passed it, and then creates a new function based on the coroutine. The first time you call it, it calls the original function until it yields. The next time, it returns from the yield and runs until the next yield. And so on.
In ComputerCraft, yielding is the same as waiting for an event.
ComputerCraft comes with the parallel library which runs two or more functions as coroutines in parallel. It does all the work for you.
You can use parallel.waitForAll or parallel.waitForAny, depending on when you want it to return.
Usage: parallel.waitForAll(constantWork, lookForKeys)

Capturing stdout in Objective C

I am using C in Objective C and I want to capture stdout to UIView from Console.
Here is the line I'm talking about:
print(stdout, v=toplevel_eval(v));
Other than you are writing in C I have no idea how much you know about C, "Unix" and Cocoa I/O - so some of this you may already know.
Here is one possible solution, it looks more complicated than it is.
Reading:
You need to understand the system calls pipe, dup2 and read.
You need to understand the GCD function dispatch_async and how to obtain a GCD queue.
pipe and dup2 are often used in conjunction with fork and exec to launch a process and write/read to/from that process standard input/output. What you will be doing uses some of the same basic ideas so looking up examples of this common pattern will help you understand how these calls work. Here are some notes from a University: Pipe, Fork, Exec and Related Topics.
Outline:
Using dispatch_async schedule a block to handle the reading and writing of the data. The block will:
Use pipe To create a pipe and dup2 To connect stdout - file descriptor 1 - it.
Enter a loop which uses read to obtain the available data from the pipe. Data read will be in a byte array.
Within the loop convert the read bytes into an NSString
Within the loop append that string to your view - you must do this on the main thread as it involves the UI, and you can do that using another dispatch_async specifying the main queue.
That is it. Your block will now execute concurrently in the background reading whatever your C code writes to the standard output and adding it to your view.
If you get stuck you can ask a new question showing the code you have written and describing what doesn't work.
HTH

When should we use run loop recursively in IOS?

I read the "IOS Developer Library" about the "Run Loops" theme, in the article, one sentence says "It is possible to run a run loop recursively". My question is in which scenario should use the recursive run loop please?
My another question is about the statement "The purpose of a run loop is to keep your thread busy when there is work to do and put your thread to sleep when there is none.". How can a run loop sleep, can the main thread's run loop sleep when no event comes? What about the second thread's situation?
one example of the nested run loop that I found from Internet is that like
below:
[NSThread detachNewThreadSelector:#selector(runOnNewThread) toTarget:self withObject:nil];
while (!end) {
NSLog(#”runloop…”);
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
NSLog(#”runloop end.”);
}
The current thread will be blocked until the work in another thread has finished. But why this happen, how the current thread can be blocked?
Can anyone answer my question?
maybe an analogy is, pretend a run loop is an infinite while loop (which it basically is), then if you made another infinite while loop inside that one, the outer while loop would never loop again because the inner one is infinite, so what they have done is made it so when you make an inifinite while loop in another, it instead goes out of the outer one, and runs along beside it (on another thread)
in response to your update:
surely it will be blocked for no other reason than the while loop doesnt have an end condition
while (!end) {
if end is controlled from another thread, then that thread would have to set end to true before the current thread can move on from this while loop.
this code just seems really bad, it keep restarting the current runloop, probably defeating it purpose

Is this a correct way of using OmniThreadLibrary - terminate the existing one then create a new one?

I use the excellent OmniThreadLibrary library to implement threaded source code parsing, the program need to abandon the existing parsing and restart the parsing whenever the source code is changed.
I do this with the code snippet shown below, is it the correct way? Do I still have to check the Terminated property of the thread in the ThreadedParseHtml function?
if FParserThread <> nil then
begin
FParserThread.RemoveMonitor;
FParserThread.Terminate(500);
end;
FParserThread := CreateTask(ThreadedParse);
FParserThread.SetParameter('SourceCode', Editor.Lines.Text);
FParserThread.MonitorWith(FParserThreadMonitor);
FParserThread.Run;
Thanks in advance!
Edit 1: Sorry for reopening this question, but I found memory leaks when FParserThread is not completed by itself by calling the Terminate method with enough time given... Any ideas as to what might cause the memory leaks? Thanks!
Edit 2: Read this blog post, I still couldn't figure what the problem might be, since after every steps in ThreadedParse the code break if Terminated is ture...
Edit 3: Answering Rob's questions:
In the OnTerminated event handler (not shown here), FParserThread is set to "nil", so by "FParser is completed by itself", I mean the if FParserThread <> nil then block is not executed, in that case FParserThread is terminated because it's parsing has been completed.
The logic behind the code is that, this is a code editor, upon any code edits there will be a thread being started to parse the source code into the internal tree presentation, in the case when a new code edit happens but the previous parsing thrad hasn't been edited, the program will first forcibly the previous parsing thread then start a new one. This maybe is not a good approach...
Edit 4: After reading this similar SO question, I changed my code to call FParserThread.Terminate without a parameter which means, if I understand it correctly, that statement will only signal the thread to end, and inside the actual thread task, I applied the logic to exit the thread execution if the Terminated property is True.
Now what's wired is that, with the help of Tracetool, I found that after calling FParserThread.Terminate the OnTaskMessage event (where I clean up the memories) would not be fired again, that's what caused the memory leaks....
You don't have to check the Terminated property in the associated task. You're calling Terminate(1), which will forcefully kill the thread if it doesn't end itself within the 1 ms window that you've specified.
However, it's really not a good idea to forcefully kill a thread. That thread might have possessed a mutex or critical section when you killed it, so killing it will leave shared data in an inconsistent state. That could have a detrimental effect on your entire program.
Better is to notify your thread that you want it to terminate, but give it a more realistic deadline for termination. Within the other thread, you should occasionally check whether the thread has been asked to terminate, and then have it terminate itself gracefully.
If the thread doesn't end within the specified time limit, then you have bigger problems, and forcefully killing it won't solve them.
OP here, after using OmniThreadLibrary for over 2 years now, my conclusion is that the proper way of stopping a OTL task is using the cancellation tokens. Code Example below.
In the caller thread (usually the main thread), call:
//this will tell (not kill) the thread identified by myTask to stop.
myTask.CancellationToken.Signal;
In the callee thread you must regularly check the task.CancellationToken.IsSignaled property, if it becomes true, exit the execution and the thread termination will be handled by the system and OTL:
if task.CancellationToken.IsSignaled then
Exit;

Sleep Lua script without halting entire program?

I'm writing a GUI that's meant to be easily customizable by the end-users. The functions are in C++ and are called from Lua. I'm trying to make a Sleep() type function that will pause the script but not the program itself.
I was able to get it working by using threads and making one for each function. However, I want it to be an individual function. As in, instead of having it part of the CreateButton function and every other function, simply having a Delay or Sleep function that only halts the script, not the entire program.
Me being a novice at Lua, I really don't know how to go about this. Any help is appreciated.
I'd look into making a state machine using coroutines and message passing. Treat each button push like a c++ string that gets passed into coroutine resume. You can then build a little state machine that switches on the message. You can then do some UI work and then put the coroutine back to sleep till something sends it another message.
This is pretty handy if you have a state machine that does UI.
pseudo code:
c_obj:wait_for_message("mouse_down");
local message = coroutine.yield();
if(message == "mouse_down") then
update draw function.
end
c_obj:wait_for_message("mouse_up");
local message = coroutine.yield();
if(message == "mouse_up") then
Update UI..
update draw function.
end
etc...
To make your busy-waiting solution more efficient, how about using select() or similar to wait for some GUI events to process, rather than spinning? It seems like something you would need to do in the GUI regardless of the scripting side of things.

Resources