views:

66

answers:

4

I need all of my threads to check periodically that they should still be running, so that they can self-terminate when the program ends. For all but one of them, this is just a matter of checking a state variable, but the last one is a user-interaction thread, and its loop will wait indefinitely on user input, only checking the state variable when the user inputs an instruction. At this point the program fails anyway since the class can't operate properly when it's not running. Ideally, though, I'd like not to get to this point.

I'm thinking that the best solution, if possible, is a timeout on the getline, but in the event that it's not possible or a good option, I'm open to any option which will allow the thread to terminate neatly.

As an aside, I see a lot of mentions of std::getline. getline seems to work whether I use the namespace or not. Is one an alias of the other, and which is the proper one to use?

Thanks, Wyatt

+1  A: 

There is no (standard) way to set a timeout on std::getline. In particular, the C++ standard library does not know the existence of threads

To answer your second question, the standards-compliant version of std::getline is the one in the namespace.

Billy ONeal
A: 

Probably the easiest way for you to do this would be to spin off yet another thread, with the sole purpose of executing getline().

google returns this result, which gives you an example, although it is heavily dependant on Win32. However, you should be able to port it to which ever thread library you are using.

a_m0d
A: 

If your threads do not have any cleanup that they need to do, an alternate solution would be to call exit when you want to end your process. exit will terminate all threads and end the process.

R Samuel Klatchko
A: 

You need another thread to signal the user thread.
How you do this will depend on the threading library you are using.

Martin York