When dealing with user input getch() from ncurses is better then multithreading? - multithreading

I am developing a game and for now I am using the getch function provided by ncurses library.
From here:
The nodelay option causes getch to be a non-blocking call. If no input is ready, getch returns ERR. If disabled (bf is FALSE), getch waits until a key is pressed.
That is, by default getch() is a blocking function and if you set nodelay to TRUE you can have a non-blocking input user function.
In another approach I can use multithreading to catch user input without blocking the course of the game.
QUESTION
Am I wasting time to rewrite my codes using threads or can I gain something (speed response, portability, etc) using that approach?
Ncurses is a nice library to make console applications but I have this doubt about user inputs.

If you have a multithreaded application with more than one thread using the display, it won't work — without some effort.
The ncurses FAQ tells more: Why does (fill in the blank) happen when I use two threads?

Related

Articulate non-blocking to blocking events in pyglet

I'm developing a game in pyglet, that scheduled by a simple text file like :
0:00:01;event1
0:00:02;event2
0:00:03;event3
The fact is that, among these events, some might be blocking (for instance event2 might consist in displaying instructions until a key is pressed). As a consequence, event3 might not be executed at the proper time (i.e., during the event2). For now, my strategy is to schedule one event after the other :
Execute the first event
Once the first event is finished, compute the remaining duration between the first and the second event (delta_duration)
Schedule the second event with a delay of delta_duration
... and so on
For now, I did not succeed in implementing properly a blocking event with this strategy. It seems that anything blocking the event_loop (like a sleep call during event2) is preventing even the graphical elements of event2 (text instructions) to be displayed. On the other hand, if I do not put any blocking routine (sleep) in the event2, I'm able to see the vertices, but the scheduler keeps on scheduling (!), and so the event3 comes too soon.
My question is : what would be a general strategy, in pyglet, to articulate non-blocking to blocking events ? More precisely, is it possible (desirable) to use multiple clocks for that purpose ? The pyglet documentation mentions that multiple clocks can be used but it is not very well explained.
I don't want a solution that is specific to my events example but, rather, general indications about the way to go.
It's really up to your program on what blocks. If you are using input from Python for the console window, then yes that will block because it's blocking execution of Python in general. If you have a label popup in the window that is waiting for input from an on_key_press window event, then that is completely different as it's not blocking the pyglet loop, it was scheduled within it.
If your event is a 20 second long math calculation, then that should probably be ran in a thread. You will probably have to separate the types of events in order to differentiate how they should be ran. It's hard to say because without a runnable example or sample of code, I am just guessing at your intentions.
Although it sounds more like you are wanting some sort of callback system. When execution of func1 is declared done, go to func2. There is nothing built into pyglet like this, you would have to have a clever use of scheduling. There are examples of this using pure python though. I personally use Twisted Deferred's for this.

Workaround for ncurses multi-thread read and write

This is what says on http://invisible-island.net/ncurses/ncurses.faq.html#multithread
If you have a program which uses curses in more than one thread, you will almost certainly see odd behavior. That is because curses relies upon static variables for both input and output. Using one thread for input and other(s) for output cannot solve the problem, nor can extra screen updates help. This FAQ is not a tutorial on threaded programming.
Specifically, it mentions it is not safe even if input and output are done on separate threads. Would it be safe if we further use a mutex for the whole ncurses library so that at most one thread can be calling any ncurses function at a time? If not, what would be other cheap workarounds to use ncurses safely in multi-thread application?
I'm asking this question because I notice a real application often has its own event loop but relies on ncurses getch function to get keyboard input. But if the main thread is block waiting in its own event loop, then it has no chance to call getch. A seemingly applicable solution is to call getch in a different thread, which hasn't caused me a problem yet, but as what says above is actually not safe, and was verified by another user here. So I'm wondering what is the best way to merge getch into an application's own event loop.
I'm considering making getch non-blocking and waking up the main thread regularly (every 10-100 ms) to check if there is something to read. But this adds an additional delay between key events and makes the application less responsive. Also, I'm not sure if that would cause any problems with some ncurses internal delay such as ESCDELAY.
Another solution I'm considering is to poll stdin directly. But I guess ncurses should also be doing something like that and reading the same stream from two different places looks bad.
The text also mentions the "ncursest" or "ncursestw" libraries, but they seem to be less available, for example, if you are using a different language binding of curses. It would be great if there is a viable solution with the standard ncurses library.
Without the thread-support, you're out of luck for using curses functions in more than one thread. That's because most of the curses calls use static or global data. The getch function for instance calls refresh which can update the whole screen—using the global pointers curscr and stdscr. The difference in the thread-support configuration is that global values are converted to functions and mutex's added.
If you want to read stdin from a different thread and run curses in one thread, you probably can make that work by checking the file descriptor (i.e., 0) for pending activity and alerting the thread which runs curses to tell it to read data.

Preemptive multithreading in Lua

I'm using lua as the scripting language for handling events in my application, and I don't want to restrict users to writing short handlers - e.g. someone might want to have one handler run an infinite loop, and another handler would interrupt the first one. Obviously, lua doesn't directly support such behavior, so I'm looking for workarounds.
First of all, I'd like to avoid modifying the engine. Is it possible to set up a debug hook that would yield once the state has reached its quota? Judging by the documentation, it shouldn't be hard at all, but I don't know if there are any caveats to this.
And second, can I use lua_close to terminate a thread as I would in actual multithreading?
I've done something similar in the past. Its completely possible to multi-thread on separate Lua states. Be sure to take a look at luaL_lock() and luaL_unlock() (plus associated setup/cleanup), as you will no doubt need this setup (a simple mutex should do the trick).
After that, it should be a fairly simple matter of creating a lock/wait/interrupt API for your handlers.

How to prevent race condition in Lua?

I am writing a Lua script that uses a library to access a hardware device with buttons. I register a callback function to handle the button presses. The code looks like:
globalvar = {}
function buttonCallback(buttonId)
...accessing globalvar
end
device.RegisterButtonCallback("buttonCallback")
while true do
end
This works.
Now I want to update the globalvar not only at a button presses but also at 1 minute intervals. Since I will need to access a network resource anyway I plan on using the socket.select call to get the 1 minute interval.
#require "socket"
globalvar = {}
function buttonCallback(buttonId)
...access globalvar
end
device.RegisterButtonCallback("buttonCallback")
while true do
socket.select(nil, nil, 60) -- wait 60 seconds
...access network
...access globalvar
end
Now I am concerned about the concurrent access of the globalvar. How can I prevent race conditions here? Most sources on multithreading in Lua advise to use continuations in cooperative scheduling but I don't see how that could be applied in my case.
Assuming the library you're using is creating another thread behind the scenes, and your only concern is about accessing globalvar from within the callback, you could avoid it by writing to a pipe in the callback, and reading from it in your select loop. In other words, use a standard POSIX-style pipe to communicate the callback back to the main thread. This is a fairly common technique when dealing with e.g. POSIX signals.
Lua is not thread-safe within a particular lua_State instance. You cannot modify a global variable from one thread while another thread is doing something else with that Lua instance. You most certainly cannot be executing two separate scripts on the same instance.
Thread safety is something you have to do outside of Lua. You cannot have the C/C++ thread that detects the button press actually call Lua code directly. It must send that data to the main thread via some thread-safe mechanism, where it will call the Lua script for them.
So I took a deep dive into the Lua books and online documentation, and contacted the author of the device driver. As the answers already indicated, it takes much more than anticipated to handle the button callbacks safely.
My approach now is to write the device driver myself and use sockets as communication channel between the device and the Lua script.
My initial approach was to use continuations as this is advocated as the Lua "replacement" for multithreading but when I read the programming in Lua book, it turns out that in order to prevent busy waits, it uses the socket.select (!). This increased my feeling that a socket-based approach is good, especially since I also need sockets for internet access in my script.

node js : there are two setInterval()

I'm Korean. My English skill too low.
In NODE.JS, there are two setInterval().
Of course, nodejs is single thread.
but, I worry about that each setInterval handles same value(or array).
To tell the truth, my circumstance has network and setInterval().
how can I controll the value. Or my worry is nothing?
You want to consider rewording this, I'm having trouble understanding what you are asking (especially in relation to network/threads), but I'm guessing you want to look into what the nodejs event loop is:
http://blog.mixu.net/2011/02/01/understanding-the-node-js-event-loop/
JavaScript runs code in what I like to call turns.
During a turn, the code that is running has full and exclusive access to all variables and the values bound to them. As no other code is or can be running, you don't have to worry about locking.
You can ignore the text below the line.
Note that although this doesn't matter in this case, if you have a process that completes over multiple turns, you should be aware that other code may have taken turns between those turns. Each turn is atomic, and there are ways to make multi-turn processes atomic but they are too complex to explain here.
Note that the concept of a turn comes from the E lang but fits so nicely in JavaScript.
only one thread is allocated to user-level
user level 에서는 오직 1 thread 만 할당 되어있다 .
so, you don't have to worry about thread confliction. or IPC
즉 thread confliction 은 고민할 필요가 없다는 얘기
if your question is not regarding this ,
then you can handle every other case easily by your application-level programming
기타 상황은 응용프로그램 레벨에서 조치 하면 될것 같음.
i'm newbie to here,
so i don't know whether language other than english is permitted or not ....

Resources