【问题标题】:How to kill a thread from another thread in vala如何从vala中的另一个线程中杀死一个线程
【发布时间】:2013-04-25 07:15:46
【问题描述】:

我有一个主线程,它创建另一个线程来执行某些工作。 主线程有对该线程的引用。即使线程仍在运行,我如何在一段时间后强制终止该线程。我找不到合适的函数调用。

任何帮助都会很重要。

我想解决的原始问题是我创建了一个线程来执行 CPU 绑定操作,这可能需要 1 秒或 10 小时才能完成。我无法预测需要多少时间。如果花费太多时间,我希望它在我愿意的时候/如果我愿意,优雅地放弃工作。我可以以某种方式将此消息传达给该线程吗??

【问题讨论】:

  • 为什么要杀死线程?你真正想做什么?
  • 我编辑了问题陈述来解释我想要做什么
  • 由于内存泄漏,您将大量数据置于未知状态。这几乎不是一个好主意。通知线程停止,并检查停止请求。

标签: multithreading vala


【解决方案1】:

假设你在谈论 GLib.Thread,你不能。即使可以,您也可能不想这样做,因为您最终可能会泄漏大量内存。

你应该做的是请求线程杀死自己。通常这是通过使用变量来指示是否已要求操作尽早停止来完成的。 GLib.Cancellable 就是为此目的而设计的,它与 GIO 中的 I/O 操作集成在一起。

例子:

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;
}

【讨论】:

  • 这里我们必须在每个循环中检查cancellable.set_error_if_cancelled () 以检查它是否已经被取消,我可以在新线程开始时做一些事情以确保它在取消时被终止,因为新线程正在执行的工作没有这种类型的简单循环,我可以在其中检查它。我无法在每个有意义的代码块之后检查这种情况。
  • 没有。为什么你不能在每个有意义的代码块之后检查它?您只需将cancellable 传递给您从线程回调调用的任何方法,并让它们抛出异常。那么它只是偶尔的cancellable.set_error_if_cancelled() 调用,这并不难。
  • 也许你问错了问题。与其问如何杀死线程(使用 glib 线程,就像我说的那样,你不能),也许你应该问如何进行长时间运行的 CPU 密集型操作,而你不能(或不会) t) 修改代码,可取消...在这种情况下,答案将是使用进程,而不是线程。
猜你喜欢
  • 2010-12-13
  • 2011-06-28
  • 2011-05-30
  • 1970-01-01
  • 1970-01-01
  • 2014-05-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多