When a simple Thread is run with just an infinite loop in it causing 100% CPU, how come is this possible?
My thread call is as follows on a QEvent in Qt dialog class, Say on a button click.
pthread_t thread_id;
pthread_create( &thread_id, NULL, DataCollectionThread, (void*) this );
And my thread procedure is,
void* DataCollectionThread( void* pParam )
{
((m_DataCollection*)pParam)->m_ReadDatafromport();
return NULL;
}
And this ReadData() contains…
while(1)
{
}
My requirement is collecting data from serial port and plot a graph continuously. But as the CPU usage is 100%, any hardware interrupt in between plotting cause the plotting to stall, as the CPU switches the task to handle interrupt.
I am calling this thread in a Qt::Dialog based class. I am pretty sure that nothing other than this is triggered. What’s wrong with this? Does a simple infinite loop causes 100% CPU consumption eh? Or Is there any problem with using pthread_create in Qt?
EDIT:For Jonathon Reinhart
This is the actual while loop
while( 1 )
{
while(( Dataisavailable))
{
//push the read data to stack
}
if(!m_DataReadable)
break;
}
One simple hack to get around this: Go to sleep for (short) periods to let the CPU do other stuff.
#include <ctime>and add somewhere in your loop:Of course, it would be better if you could explicitly sleep until you have actual work to do (more input to read, a full queue to trim). But adding in short sleeps will probably be sufficient.
It might make sense to look into your
m_pDataProviderobject’s implementation. Check for or add a method allowing you to sleep until there’s more data. If you’re just reading from a character device (e.g. ttyS0),pollorselectmight be useful here.