[cairo-commit] [cairo-www] src/threaded_animation_with_cairo.mdwn

Carl Worth cworth at freedesktop.org
Thu Jan 17 18:45:13 PST 2008


 src/threaded_animation_with_cairo.mdwn |    1 -
 1 file changed, 1 deletion(-)

New commits:
commit 5f32837e81fe4919a9c453bdb0b7d40b5dc2b812
Author: Carl Worth <cworth at freedesktop.org>
Date:   Thu Jan 17 18:45:13 2008 -0800

    web commit by Albert: fds

diff --git a/src/threaded_animation_with_cairo.mdwn b/src/threaded_animation_with_cairo.mdwn
index 19b3efb..78206b9 100644
--- a/src/threaded_animation_with_cairo.mdwn
+++ b/src/threaded_animation_with_cairo.mdwn
@@ -4,4 +4,38 @@ Complex animations with cairo and GTK+ can result in a laggy interface.  This is
 
 One solution is to hand off all the processor-intensive drawing to a separate thread, thus freeing the `gtk_main()` thread to respond to events.
 
-This tutorial will show you how to safely implement multi-threaded c code to draw a processor intensive animation to a `gtk_window`.
\ No newline at end of file
+This tutorial will show you how to safely implement multi-threaded c code to draw a processor intensive animation to a `gtk_window`.
+
+##GTK+ and Thread Safety
+GTK+, by default, is not thread safe.  However, with a few commands, it can be made (what the GTK+ documentation calls) _thread aware_.  This basically means that GTK+ works fine in a multithreaded environment as any calls made to a gtk object outside of `gtk_main()` are protected by `gdk_threads_enter()` and `gdk_threads_leave()` commands.[1]
+
+##Creating a _thread-aware_ `main()`
+
+In order to make GTK+ thread aware, we use the `g_thread_init(NULL)` and `gdk_threads_init()` commands.  After that, any calls to gtk need to be encased between `gdk_threads_enter()` and `gdk_threads_leave()`.  This _includes_ `gtk_main()`!  (Because `gtk_main()` is called between `gdk_threads_enter()` and `gdk_threads_leave()`, any
+callback functions are automatically protected, so the `gdk_threads_enter()` and `gdk_threads_leave()` functions shouldn't be used again until we launch a different thread.)
+
+A minimal thread-aware gtk program might look like:
+
+
+	#include <gtk/gtk.h>
+
+	int main (int argc, char *argv[]){
+
+		//we need to initialize all these functions so that gtk knows
+		//to be thread-aware
+		g_thread_init(NULL);
+		gdk_threads_init();
+		gdk_threads_enter();
+
+		gtk_init(&argc, &argv);
+
+		GtkWidget *window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
+		g_signal_connect(G_OBJECT(window), "destroy", G_CALLBACK(gtk_main_quit), NULL);
+
+		gtk_widget_show_all(window);
+
+		gtk_main();
+		gdk_threads_leave();
+
+		return 0;
+	}
\ No newline at end of file


More information about the cairo-commit mailing list