Thread safe GUI programming

event-programmingguimultithreading

I have been programming Java with swing for a couple of years now, and always accepted that GUI interactions had to happen on the Event Dispatch Thread. I recently started to use GTK+ for C applications and was unsurprised to find that GUI interactions had to be called on gtk_main. Similarly, I looked at SWT to see in what ways it was different to Swing and to see if it was worth using, and again found the UI thread idea, and I am sure that these 3 are not the only toolkits to use this model. I was wondering if there is a reason for this design i.e. what is the reason for keeping UI modifications isolated to a single thread. I can see why some modifications may cause issues (like modifying a list while it is being drawn), but I do not see why these concerns pass on to the user of the API. Is there a limit imposed by an operating system? Is there a good reason these concerns are not 'hidden' (i.e. some form of synchronization that is invisible to the user)? Is there any (even purely conceptual) way of creating a thread safe graphics library, or is such a thing actually impossible?

I found this http://blogs.operationaldynamics.com/andrew/software/gnome-desktop/gtk-thread-awareness which seems to describe GTK differently to how I understood it (although my understanding was the same as many people's) How does this differ to other toolkits? Is it possible to implement this in Swing (as the EDT model does not actually prevent access from other threads, it just often leads to Exceptions)

Best Answer

a single looper thread is easier to implement, understand and use compared to multiple threads, (like separate painter eventcallback threads)

because with multithreading in the GUI all access to a GUI component needs to be synchronized (only exception is immutable stuff), this would then become a major bottle neck especially in times where it was prohibitevly expensive to acquire a lock or in tightly coupled frameworks

then there's also that if the eventlisteners can be notified on any thread (whichever one happened to poll the event queue) you would require thread safety to be applied to the underlying model (this is hard to get right). Even the paint-eventcallback segregation example above would need read-write synchronization.

one thing to note is that most frameworks have the idea of a background thread to use for long calculations and IO (like SwingWorker) or atleast a way to add a event to call a certain function on the event thread (generally called invoke)

Related Topic