2
votes

In Free-Pascal I'm going to create a cross platform console program which will do most of it's work in a bunch of threads (TThread).

The main program is only used for recieving a few user commands now and then and executing these (and to keep the whole program running).

This loop as the program's main loop works perfectly on both Windows and Linux with no cpu usage:

repeat
  Write('> ');
  ReadLn(s);
  // execute command
until s='exit';

But I need the threads to command the main program to do some work. This means I need a way to stop the ReadLn from another thread to go on and check for a command flag. If I could somehow send an Enter-keypress to trick ReadLn to end it would be fine.

Are there other ways to make a cross platform main loop which listens for a user string or key presses and at the same time will be commandable from other threads?

1
Why can the threads not do the work? - Martin James
It's "hanging" in the ReadLn statement which seems to satisfy both Windows and Linux to not go into 100% cpu usage as would be the case if I did a "repeat until keypressed". - Thomas Munk
We get that, but if there is work to be done, why has the 'main program' have to do it? Why can the threads not do it? - Martin James
Comment #2 was for a Q which is gone. The threads might do the work, but one of the jobs require a lot of status writing to the console and no user input meanwhile. So an interruption of ReadLn is required anyway. - Thomas Munk

1 Answers

2
votes

Yes, use unit keyboard. This abstracted keyboard support allows to peek for events (keys) , and this means a boolean set in a thread could make it exit a loop.

See the keyboard unit in the (rtl) manual and textconsole games (fpctris, samegame) that come with a standard FPC install.