ThreadPool
Object Hierarchy:
Description:
[
Compact ]
public class ThreadPool<
T>
The ThreadPool struct represents a thread pool.
It has three public read-only members, but the underlying struct is bigger, so you must not copy this struct.
Example:
class Worker {
public string thread_name { private set; get; }
public int x_times { private set; get; }
public int priority { private set; get; }
public Worker (string name, int x, int priority) {
this.priority = priority;
this.thread_name = name;
this.x_times = x;
}
public void run () {
for (int i = 0; i < this.x_times ; i++) {
stdout.printf ("%s: %d/%d\n", this.thread_name, i + 1, this.x_times);
Thread.usleep (1000000); // wait a second
}
}
}
public static int main (string[] args) {
try {
ThreadPool<Worker> pool = new ThreadPool<Worker>.with_owned_data ((worker) => {
// Call worker.run () on thread-start
worker.run ();
}, 3, false);
// Define a priority (otpional)
pool.set_sort_function ((worker1, worker2) => {
// A simple priority-compare, qsort-style
return (worker1.priority < worker2.priority)? -1 : (int) (worker1.priority > worker2.priority);
});
// Assign some tasks:
pool.add (new Worker ("Thread 1", 5, 4));
pool.add (new Worker ("Thread 2", 10, 3));
pool.add (new Worker ("Thread 4", 5, 2));
pool.add (new Worker ("Thread 5", 5, 1));
uint waiting = pool.unprocessed (); // unfinished workers = 4
uint allowed = pool.get_max_threads (); // max running threads = 3
uint running = pool.get_num_threads (); // running threads = 3
stdout.printf ("%u/%u threads are running, %u outstanding.\n", running, allowed, waiting);
} catch (ThreadError e) {
stdout.printf ("ThreadError: %s\n", e.message);
}
return 0;
}
valac --pkg glib-2.0 GLib.ThreadPool.vala
Content:
Static methods:
- public static void set_max_unused_threads (int max_threads)
Sets the maximal number of unused threads to max_threads.
- public static int get_max_unused_threads ()
Returns the maximal allowed number of unused threads.
- public static uint get_num_unused_threads ()
Returns the number of currently unused threads.
- public static void stop_unused_threads ()
Stops all currently unused threads.
- public static void set_max_idle_time (uint interval)
This function will set the maximum interval that a thread
waiting in the pool for new tasks can be idle for before being stopped.
- public static uint get_max_idle_time ()
This function will return the maximum interval that a thread
will wait in the thread pool for new tasks before being stopped.
Creation methods:
Methods: