Hi,

I'm writing a C++ single-threaded Unix daemon that listens for data arriving at a port. The whole application logic is contained into an infinity loop. The problem is that the daemon consumes a lot of CPU cycles, specifically because the loop is being continuously executed. I’ve looking around for a good solution to this problem, but I haven’t found any clue on how to handle this situation. I suppose that a good approach could be to sleep the loop for a few milliseconds and let the system to use some CPU cycles before going to the next loop step.
The question is: Do anybody know if this approach is correct? And, if is it correct, do anybody know how many seconds should the application sleep?
Any help will be appreciated.

Thanks in advance,

Erik

Well, what you want to implement is called multi-threading applications.
It is OS dependent. So you may like to search a bit more about this.

Sorry, but I can't see the necessity for multi-threading this application. The logic fits well in a single-threaded application. What I need is to minimize the CPU usage; I can't see how this can be done using more threads. Can you be more specific please?

Evidently it's impossible to answer the question in common case. It depends on this port nature and features. If no underlied system provided events to wait and react on the port activity the only approach is a "busy wait" (probably it's your case).
Possible approaches:
- Set the lowest (at least lower) priority to your process - let it plays an idle loop role.
- Add passive wait periods (sleeping) - the proper time delay depends on the system shedule characteristics and permissible data stream processing degradation.

Hi, thanks a lot for your answers. Finally, I have a clearly view on where my problem is. Indeed, neither I can't block the port nor catch events from it. I'm using a third application which acts as a bridge between my application and the port. This application provides an API and the only thing I can do is to poll the application for changes in the port. I think that the most reasonable approach is to use the “busy wait” as was proposed by ArkM. I'll check the way for doing this in Linux, which is the underlying platform. Once again, thanks a lot.

Erik

This question has already been answered. Start a new discussion instead.