To the best of my knowledge, event-driven programs require a main loop such as

while (1) {

} 

I am just curious if this while loop can cost a high CPU usage? Is there any other way to implement event-driven programs without using the main loop?

有帮助吗?

解决方案

Your example is misleading. Usually, an event loop looks something like this:

Event e;
while ((e = get_next_event()) != E_QUIT)
{
    handle(e);
}

The crucial point is that the function call to our fictitious get_next_event() pumping function will be generous and encourage a context switch or whatever scheduling semantics apply to your platform, and if there are no events, the function would probably allow the entire process to sleep until an event arrives.

So in practice there's nothing to worry about, and no, there's not really any alternative to an unbounded loop if you want to process an unbounded amount of information during your program's runtime.

其他提示

Usually, the problem with a loop like this is that while it's doing one piece of work, it can't be doing anything else (e.g. Windows SDK's old 'cooperative' multitasking). The next naive jump up from this is generally to spawn a thread for each piece of work, but that's incredibly dangerous. Most people would end up with an executor that generally has a thread pool inside. Then, the handle call is actually just enqueueing the work and the next available thread dequeues it and executes it. The number of concurrent threads remains fixed as the total number of worker threads in the pool and when threads don't have anything to do, they are not eating CPU.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top