Vala线程池的正确使用方法是什么?
我正在尝试使用 GLib.ThreadPool
s 在 Vala,但在搜索 Google 代码和现有文档后,我找不到任何好的使用示例。我自己尝试使用它们会导致未处理的 GLib.ThreadError 。
例如,考虑以下 26 行,它们线程化整数范围的乘法。
threaded_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。
I'm trying to use GLib.ThreadPool
s in Vala, but after searching Google Code and the existing documentation, I can't find any good examples of their use. My own attempts at using them result in unhandled GLib.ThreadError
s.
For example, consider the following 26 lines, which thread the multiplication of integer ranges.
threaded_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));
}
Compiling them with valac --thread threaded_multipy.vala
works fine... but spews warnings at me. Given the dangers of multithreading, this makes me think I'm doing something wrong and might explode in my face eventually.
Does anyone know who to use GLib.ThreadPool
correctly? Thanks for reading, and more thanks if you have an answer.
edit: I thought in might be because of my compiling machine, but no, Thread.supported()
evaluates to true here.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我没有看到你的代码有什么问题。编译器警告是关于未捕获 ThreadErrors 的。你可能应该这样做。只需添加一个 try 并捕获,如下所示:
I don't see anything wrong with your code. And the compiler warnings are about not catching ThreadErrors. Which you probably should do. Just add a try and catch like this: