Search code examples
multithreadingvala

How to kill a thread from another thread in vala


I have a main thread which creates another thread to perform some job. main thread has a reference to that thread. How do I kill that thread forcefully some time later, even if thread is still operating. I cant find a proper function call that does that.

any help would be appreciable.

The original problem that I want to solve is I created a thread a thread to perform a CPU bound operation that may take 1 second to complete or may be 10 hours. I cant predict how much time it is going to take. If it is taking too much time, I want it to gracefully abandon the job when/ if I want. can I somehow communicate this message to that thread??


Solution

  • Assuming you're talking about a GLib.Thread, you can't. Even if you could, you probably wouldn't want to, since you would likely end up leaking a significant amount of memory.

    What you're supposed to do is request that the thread kill itself. Generally this is done by using a variable to indicate whether or not it has been requested that the operation stop at the earliest opportunity. GLib.Cancellable is designed for this purpose, and it integrates with the I/O operations in GIO.

    Example:

    private static int main (string[] args) {
      GLib.Cancellable cancellable = new GLib.Cancellable ();
      new GLib.Thread<int> (null, () => {
          try {
            for ( int i = 0 ; i < 16 ; i++ ) {
              cancellable.set_error_if_cancelled ();
              GLib.debug ("%d", i);
              GLib.Thread.usleep ((ulong) GLib.TimeSpan.MILLISECOND * 100);
            }
    
            return 0;
          } catch ( GLib.Error e ) {
            GLib.warning (e.message);
            return -1;
          }
        });
    
      GLib.Thread.usleep ((ulong) GLib.TimeSpan.SECOND);
      cancellable.cancel ();
    
      /* Make sure the thread has some time to cancel.  In an application
       * with a UI you probably wouldn't need to do this artificially,
       * since the entire application probably wouldn't exit immediately
       * after cancelling the thread (otherwise why bother cancelling the
       * thread?  Just exit the program) */
      GLib.Thread.usleep ((ulong) GLib.TimeSpan.MILLISECOND * 150);
    
      return 0;
    }