In my TCP multithreaded server written in C, I have multiple threads with infinite loops checking for new inputs from thread safe queue and then doing their jobs. pseudocode:
void jobThread(void * arg){
CustomQueue queue = (CustomQueue) arg;
while(1){
if(customQueueNotEmpty(queue)){
doSomeJob(getItemFromQueue(queue))
}
}
}
I have multiple threads running like this, but number of threads is directly controlled with program. It is not like threads are spawned for each user online or job to be done, but rather user sessions and game-jobs are added dynamically to prespawned threads. Most probably the number of threads will be limited by number of CPUs on host machine.
My question is about the while(1)
statement. In case when there are many users connected and many jobs to be done this is probably fine, because all of the CPU time is just used to do the job. But otherwise, most of the CPU time gets burned just to loop and check queue.
Should I add sleep()
to make thread less CPU exhaustive? Or should I not use while(1)
since it is not a good practice? Or do I not care at all since every thread can get its own CPU core and therefore does not slow other threads?
Edit: Philiph's answer suggested using condition variables which I imagine using something like this:
void jobThread(void * arg){
CustomQueue queue = (CustomQueue) arg;
while(1){
while(customQueueNotEmpty(queue)){
doSomeJob(getItemFromQueue(queue))
}
pthread_cond_wait(cond); //when queue is empty wait for other thread to reawake this
}
}
and then in other thread that fills the queue call:
putInQueue(quueue, item);
pthread_cond_signal(cond);
when new message arrives. But what about case, when consumer thread reads queue as being empty just before the moment of producer thread filling it with new message. Then the consumer thread would wait without processing the new message and only awakening after yet another message arrives to awake the consumer and make it process both new messages.