Project directory structure

Jef Driesen jefdriesen at telenet.be
Thu Apr 4 05:11:48 PDT 2013


On 2013-04-03 21:13, Dirk Hohndel wrote:
> So how would this be handled from C code? Right now (because of
> limitations with the way Gtk does things) the main thread does 
> something
> like this:
>
> 	while (!import_thread_done) {
> 		if (!import_thread_cancelled) {
> 			int result;
> 			g_timeout_add(100, timeout_func, dialog);
> 			update_progressbar(&data->progress, progress_bar_fraction);
> 			update_progressbar_text(&data->progress, progress_bar_text);
> 			result = gtk_dialog_run(dialog);
> 			switch (result) {
> 			case GTK_RESPONSE_CANCEL:
> 				import_thread_cancelled = TRUE;
> 				progress_bar_text = _("Cancelled...");
> 				break;
> 			default:
> 				/* nothing */
> 				break;
> 			}
> 		} else {
> 			update_progressbar(&data->progress, progress_bar_fraction);
> 			update_progressbar_text(&data->progress, progress_bar_text);
> 			usleep(100000);
> 		}
> 	}
>
> And we use the global variables import_thread_cancelled,
> import_thread_done progress_bar_text and progress_bar_fraction to
> communicate from the download thread to the UI thread.
> The stupid timeout mechanism is working around Gtk's inability to do 
> the
> updates from a separate thread (I understand the same is true for 
> Qt).

Actually, the correct way to implement this on Gtk is as follows. In 
the download thread (or any other thread which is not running the Gtk 
mainloop), you call g_idle_add(function,data). The result is that your 
function is dispatched to the mainloop, and thus called on the UI 
thread. From there it's safe to call Gtk+ functions. Of course you have 
to take care to protect your data with a mutex. In most cases, you can 
just malloc the data, and free it again when the function is called. 
Then you don't need a mutex.

Thus in the download thread, every time you receive a progress event, 
you can notify the UI thread about the new value and update the progress 
bar from the UI thread. The same mechanism can be used to notify the UI 
thread when the download is finished. For the cancel button, you can set 
some flag and then check that variable from the download thread 
(protected by a mutex of course).

I assume Qt will have a similar mechanism, but I don't know Qt at all.

Jef


More information about the subsurface mailing list