www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Terminating a thread (which is blocking)

reply Timothy Foster <timfost aol.com> writes:
I've started a thread at the beginning of my program that waits 
for user input:

`thread = new Thread(&checkInput).start;`

`static void checkInput(){
     foreach (line; stdin.byLineCopy) { ... }
}`

I need to stop checking for user input at some point in my 
program but I'm not sure how to kill this thread. 
`thread.yield();` called from my main thread doesn't kill it and 
I'm not sure how to send a message to the input checking thread 
to get it to terminate itself when `stdin.byLineCopy` just sits 
there and blocks until user input is received.
Aug 24 2017
parent Eugene Wissner <belka caraus.de> writes:
On Thursday, 24 August 2017 at 07:23:15 UTC, Timothy Foster wrote:
 I've started a thread at the beginning of my program that waits 
 for user input:

 `thread = new Thread(&checkInput).start;`

 `static void checkInput(){
     foreach (line; stdin.byLineCopy) { ... }
 }`

 I need to stop checking for user input at some point in my 
 program but I'm not sure how to kill this thread. 
 `thread.yield();` called from my main thread doesn't kill it 
 and I'm not sure how to send a message to the input checking 
 thread to get it to terminate itself when `stdin.byLineCopy` 
 just sits there and blocks until user input is received.
If you're on Linux, you can try pthread_kill. Otherwise don't block. Define a shared boolean variable that says if the thread should stop. Wait for the input for some time and break, check the condition variable, try to read again or break and so on.
Aug 25 2017