C GTK+ Event signal on startup
I'm writing a countodown timer. It consists of a single windows with a label in it, where the time is displayed. The "timer()" (in the code below) is spawned as a thread. This works perfectly in a linux environment, but as far as I'm concerned GTK does not support multithreading under windows (correct me if I am wrong). Is it possible to spawn the "timer()" without using threads, e.g. by calling a signal when the开发者_开发问答 main_window appears?
#include <stdio.h>
#include <time.h>
#include <unistd.h>
#include <string.h>
#include <pthread.h>
#include <gtk/gtk.h>
GtkWidget *window;
GtkWidget *label;
pthread_t timer_thread;
void* timer()
{
while(1)
{
// some code here to calculate time
gtk_label_set_markup ((GtkLabel*)label, time_c);
sleep(1);
}
}
static gboolean delete_event( GtkWidget *widget, GdkEvent *event, gpointer data )
{
return FALSE;
}
static void destroy( GtkWidget *widget, gpointer data )
{
gtk_main_quit ();
}
int main(int argc, char **argv)
{
g_thread_init(NULL);
gdk_threads_init();
gdk_threads_enter();
gtk_init (&argc, &argv);
window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
g_signal_connect (window, "delete-event", G_CALLBACK (delete_event), NULL);
g_signal_connect (window, "destroy", G_CALLBACK (destroy), NULL);
label = gtk_label_new("");
gtk_container_add (GTK_CONTAINER (window), label);
gtk_widget_show (label);
gtk_widget_show (window);
pthread_create(&timer_thread, NULL, timer, NULL);
gtk_main ();
gdk_threads_leave();
return 0;
}
I tried doing this, the timer() spawned correctly, but the main window never appeared:
static void timer( GtkWidget *widget, gpointer data )
{
while(1)
{
g_print("something"); //for checking
// some code here to calculate time
gtk_label_set_markup ((GtkLabel*)label, time_c);
sleep(1);
}
}
int main(int argc, char **argv)
{
g_signal_connect (window, "show", G_CALLBACK (timer), NULL);
}
Thanks in advance!
You would be better off using a timer for that. Look into g_timeout_add
. There's an example here: GTK+ events and signals.
Use g_timeout_add
and a GTimer
. Initalize your GTimer, and on your timeout callback, call g_timer_elapsed. Relying only on the time used when calling g_timeout_add would cause timing inacurracy.
精彩评论