Switching threads

The ways that different toolkits and languages handle multithreading and graphical updates vary substantially. The following illustrations aim to highlight the complexity of this problem, in case you are not familiar with these constraints. The specifics sometimes vary based on language or version, but the concepts are usually consistent, otherwise software developed using the APIs would be very difficult to manage.

For our first example, consider an application written in Java. Its convention is that the graphics and user interaction are handled by a single event dispatch thread. Therefore, any change you wish to make to the user interface needs to be pushed to this thread using SwingUtilities.invokeLater():

SwingUtilities.invokeLater(new Runnable() {
public void run() {
button.SetText("Updated!");
}
});

The approach for working with Apple's operating systems is slightly different. Applications built with AppKit or UIKit (which are used for desktop and mobile applications respectively) start the user interface event handling on the main thread. This means that after the interface is configured, all processing must be handled on a background thread and changes to the user interface must be executed on the main thread. The objective-C block construct (for encapsulating a single behavior) makes this a little easier, but the code is still non-trivial:

dispatch_async(dispatch_get_main_queue(), ^{
[button setTitle:@"Updated!" forState:UIControlStateNormal];
});

Applications using GTK (which supports building apps for various different platforms) have a similar restriction. For those, the graphical updates must be processed on whichever thread you invoked gtk_init() and gtk_main(). For such applications, the thread handling provided by GLib will help to manage multithreading in your application, but you have to set this up in the interface initialization code:

...
gtk_init(&argc, &argv);
...
gdk_threads_enter();
gtk_main();
gdk_threads_leave();
...

Then, you can use the gdk thread helpers to manage background updates as follows:

gdk_threads_enter();
gtk_button_set_label(GTK_BUTTON(label), "Updated!");
gdk_threads_leave();
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.17.128