【问题标题】:What is proper use of Vala thread pools?Vala线程池的正确使用是什么?
【发布时间】:2011-10-16 23:08:17
【问题描述】:

我正在尝试在 Vala 中使用 GLib.ThreadPools,但在搜索 Google Code 和 the existing documentation 之后,我找不到任何使用它们的好例子。我自己尝试使用它们的结果是未处理的GLib.ThreadErrors。

例如,考虑以下 26 行,它们线程化整数范围的乘法。

thread_multiply.vala

class Range {
    public int low;
    public int high;

    public Range(int low, int high) {
        this.low = low;
        this.high = high;
    }
}

void multiply_range(Range r) {
    int product = 1;
    for (int i=r.low; i<=r.high; i++)
        product = product * i;
    print("range(%s, %s) = %s\n",
          r.low.to_string(), r.high.to_string(), product.to_string());
}

void main() {
    ThreadPool<Range> threads;
    threads = new ThreadPool<Range>((Func<Range>)multiply_range, 4, true);
    for (int i=1; i<=10; i++)
        threads.push(new Range(i, i+5));
}

使用valac --thread threaded_multipy.vala 编译它们可以正常工作...但会向我发出警告。考虑到多线程的危险,这让我觉得我做错了什么,最终可能会在我的脸上爆炸。

有谁知道正确使用GLib.ThreadPool 吗?感谢您的阅读,如果您有答案,更感谢您。

编辑:我认为可能是因为我的编译器,但不是,Thread.supported() 在这里评估为 true。

【问题讨论】:

    标签: multithreading threadpool compiler-warnings glib vala


    【解决方案1】:

    我认为您的代码没有任何问题。编译器警告是关于不捕获 ThreadErrors。你可能应该这样做。只需像这样添加一个 try and catch :

     try {
        threads = new ThreadPool<Range>((Func<Range>)multiply_range, 4, true);
        for (int i=1; i<=10; i++)
        threads.push(new Range(i, i+5));
      }
     catch(ThreadError e) {
        //Error handling
        stdout.printf("%s", e.message);
     }
    

    【讨论】:

      猜你喜欢
      • 2010-11-14
      • 2012-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-03
      • 2011-11-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多