[ back to toc ]


Date: 2002/05/02 12:01

Hi Peter,
I'm coding in C on Linux, and I'm trying to implement some posix threads.
In my current program, I'm starting 7 threads from a funciton called by
main. Each thread is supposed to be a continues process (scanning a
directory for new files, updating a Database, etc).
My problem is that when the function ends and main returns 0, it kills all
my thread when the program then terminates (being the owner process).
I then added a while(true); loop after starting all the threads in order
to stop the program from terminating and therefore keeping my threads
The issue is that when I start the program and run a 'ps', The program's
main thread (with the infinite loop) takes 75 - 80% of my system's CPU.
Is there anyway that I could move the program to the background, that wont
eat my resources and keep my threads alive at the same time?


The thread is not a spearate process, but part of the process. Therefore
if you exit the process returning from main() then all memory, handles,
threads and other resources that are allocated to the process are freed.

If you make a ' while(1); ' loop that certainly will eat CPU. But you can
make a ' while(1)sleep(100); loop that will not consume CPU only every 100

Even though this is not a really good solution. Your program is a kind of
daemon, that has to be designed to be able to stop. Thus you have to
implement semaphores/mutexes that can be used to signal for the threads to
finish as soon as they can and the main thread wait for the sub-threads to
stop and when all other threads stopped stop the process itself. This is
needed to ensure that killing the process does not loose any data or leave
some partially written adn thus corrupted file behind.


[ back to toc ]