views:

75

answers:

1
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?

+1  A: 

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.

WhirlWind
Is it possible to make some kinds of daemon threads that will exit automatically when main thread exits?
httpinterpret
@httpinterpret it depends on the specifics of what you are doing; you have to be very careful that you don't leave things in an inconsistent state. GThreadPool, or condition variables may be what you are looking for. You may wish to put in a bit of high-level detail on what you're trying to multithread, so we can think about it.
WhirlWind
My posted demo is exactly what I'm doing.
httpinterpret
Then I suggest you add a check in the while loop that updates whether the loop should continue, or the function should exit. The point of threads is that they are asynchronous, so you can't necessarily control them at any given point from another function.
WhirlWind
I don't know if there is some API akin to `kill PID`
httpinterpret
Threads are different from processes. If a process misbehaves, it is the responsibility of the operating system to be able to deal with it. It is the responsibility of the threads within a process to play nicely with each other. This is part of what makes threads lower overhead: they are self-managing. When programming with threads, you have to make them behave in a way that is friendly to the application as a whole, including making ways for them to exit cleanly. Killing threads tends to leave things in an inconsistent state which can cause application problems.
WhirlWind
But in python,it's possible to create daemon threads that'll exit automatically when main thread exists.
httpinterpret
@httpinterpret there is no way to do this with pthreads or glib, but you could call exit() from main, which will cause everything to quit.
WhirlWind
Will `Thread1` auto exit when the windows is closed if `main` -> `WinMain` ?
httpinterpret
Yes, it will, as long as the process exits, though, I'd recommend you synchronize using a cleaner method.
WhirlWind