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.
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.
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:
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);
}