2

I have checked several questions and answers here and there (example), and I can't seem to find a solution or approach to what I am looking for.

I have a program that as soon as it begins, it will never stop unless the user inputs whatever.

So threads are going and doing some calculus, and it never stops (I want it to be that way).

But I want to be able to make it stop as soon as the user inputs something, and then, show the final results (this is not difficult).

So my main question is: is there a way to be listening to an input at the same time as the program is running and showing the process? (Imagine, showing numbers going 1 by 1 (1,2,3,4,5), printing them, and at the same time, be able to input whatever value.)

(What I thought it is making in the #pragma omp parallel for, is use a shared variable (a flag), and an if inside the loop, so as soon as the flag is true or false, break;.)

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
M.K
  • 1,464
  • 2
  • 24
  • 46
  • 3
    OpenMP supports what it calls *cancellation points* which might be what you are looking for. Hit your favourite search engine, or even have a closer look around here. – High Performance Mark Oct 26 '18 at 10:42
  • 1
    Cancellation is cerainly the right way to approach this, as it provides certain guarantees to the programmer that simple flags with a `break` statement will not be able to achieve. Esp. the OpenMP memory model will require extensive and correct usage of `flush` directives to communicate the changed flag between the threads w/o performance penalties. – Michael Klemm Mar 12 '19 at 10:05

1 Answers1

1

You can stop your program by sharing a global flag. Let's call it should_stop.

By default, it is set to false.

Then, after each loop of computation (I suppose there is a main loop somewhere; the same pattern works for tasks as well) on your master thread, check the keyboard state. If there is an available character (be sure you're not using a blocking call. Just poll the buffer instead), set the flag.

Then on all threads, after they finish their current step, check the state of the flag, and if it's set, finish the computation.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Matthieu Brucher
  • 21,634
  • 7
  • 38
  • 62
  • Please see the comment above. The OpenMP memory will interfere with this, so that this solution likely will not work correctly or will be non-portable. – Michael Klemm Mar 12 '19 at 10:06