Re: interrupting a big loop



Allin Cottrell wrote:
When my (gtk) app is engaged in a time-consuming loop process, I'd
like to offer the user the chance of breaking out if he/she loses
interest.  The pseudo-code is something like:

for (i=0; i<LARGE_NUMBER; i++) {
   if (break_condition()) break;
   /* do something complicated */
}

where "break_condition()" checks whether a particular quit key has
been pressed or quit button has been clicked.

My puzzle is over how exactly to link the break_condition() function
with the appropriate callback associated with the keystroke or
button-click.  Do I need something like g_main_context_iteration()?

   If you take this approach (which is less complicated than using threads,
and IMO preferable when possible), yes.

You'll need to:

for (i=0; i<LARGE_NUMBER; i++) {
    /* process Gtk events
     */
    while (gtk_events_pending())
        gtk_main_iteration();

    /* It is possible that your callback
     * `on_cancel_button_clicked()' was called
     * during `gtk_main_iteration()'.
     */
    if (should_stop == TRUE) break;

    /* do something complicated */
}

    Ofcourse there are other ways, you could put your expensive
itterations in a timeout function and call `g_source_remove()'
in your `on_cancel_button_clicked()' callback for example.

Cheers,
                                        -Tristan





[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]