Re: interrupting a big loop



On Wed, 19 May 2004, Tristan Van Berkom wrote:

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 */
}

Thank you, this is just the sort of thing I was groping for.  I have
one more question.

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

What's the best way of implementing this?  Make "should_stop" a global
boolean that is initially set to FALSE, and is set TRUE within the
cancel button callback?  Or can one avoid a global?

Allin Cottrell



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