httpinterpret
httpinterpret

Reputation: 6719

How do I make child thread exit when main thread exit?

void forloop2()
{
    int i = 0;
    while(TRUE)
    {
        printf("forloop2\n");
    }
}

int main() {
    GThread          *Thread1;
    GtkWidget *window;
    g_thread_init(NULL);
    gdk_threads_init();
    gdk_threads_enter ();
    Thread1 = g_thread_create((GThreadFunc)forloop2, NULL, TRUE, NULL);
    gtk_init(NULL, NULL);
    window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
    gtk_widget_show_all (window);
    gtk_main();
    g_thread_join(Thread1);
    gdk_threads_leave ();
}

When I close the window, how to make Thread1 also exit?

Upvotes: 2

Views: 577

Answers (1)

WhirlWind
WhirlWind

Reputation: 14112

Clear some condition in main that the loop in forloop2() checks on each iteration. When you want to exit from main, set that condition, then call g_thread_join() on Thread1. Since forloop2() checks when it sees that condition, it will exit, causing it to join, and main will proceed to exit.

Upvotes: 1

Related Questions