Re: How to properly exit a thread?



Yes, you are right. The thread is  always  running and reading new 
data from a file and  waiting for the new data to be consumed and then 
read more new data.
I can't make the thread joinable, because the thread is always running 
during program execution. What I want to do is to exit the thread just 
before the program is going to exit. That's what I don't know how to 
achieve.
Xiangfei,

This is a design issue. You'll need someway to signal your thread to that its time to finish up. There are some different ways of doing this, but they all depend on your design. The immediately obvious approach would be doing something like, when you consume the last batch of new data, find a way to tell your thread to die.
Just because your thread is running continously does not mean that it 
can't be joinable.  In almost all cases, threads are indeed joinable.  
The most common case when you might want to create a detached thread 
(one thats not joinable) is when the detached thread needs to run beyond 
the lifetime of the creating thread.  And this isn't even always true.  
As much as I've ever read, basically, the only reason to create a thread 
detached is to explicitly say "I never want to join this thread"  Which 
in your case is not *necessarily* true.
If you've only got the one thread working, then my advice would be this:

In your read/consume cycle, find a place to tell the read_new_data thread that this is the last chunk to process and let it die, then call read->join() in your main thread to wait for it to join.
If thats impossible for some reason, you'll need to share a synchronized 
variable that can be used as a flag to tell the worker thread to exit, 
and I'd still reccommend calling read->join() in that case.
Getting anymore specific without code is gonna be hard, and if you're 
still having trouble I recommend reading "Multithread Programming with 
Pthreads" by Lewis and Berg.
Hope that helps.

Paul



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]