Read from terminal when enter is pressed, but do other stuff in the mean time...
Ali Çehreli via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Thu Jul 13 10:15:07 PDT 2017
On 07/13/2017 08:52 AM, Dustmight wrote:
> How do I read in input from the terminal without sitting there waiting
> for it? I've got code I want to run while there's no input, and then
> code I want to act on input when it comes in. How do I do both these
> things?
If you're fine with buffered input, i.e. the user has to press Enter
before the input is visible to the program, then std.concurrency works
pretty well.
Enter lines to the following program. It will exit when you send the
line "done".
import std.concurrency;
import std.stdio;
import core.thread;
import std.range;
struct Done {
}
struct Message {
string line;
}
void worker() {
bool done = false;
while (!done) {
receive(
(Message message) {
auto line = message.line;
writefln("Received \"%s\"", line);
while (!line.empty) {
writeln(line.front);
line.popFront();
Thread.sleep(500.msecs);
}
writefln("Done with \"%s\"", message);
},
(Done message) {
writefln("Bye...");
done = true;
});
}
}
void main() {
auto w = spawn(&worker);
foreach (line; stdin.byLineCopy) {
if (line == "done") {
w.send(Done());
break;
}
w.send(Message(line));
}
thread_joinAll();
}
Ali
More information about the Digitalmars-d-learn
mailing list