Thread
Object Hierarchy:
Description:
[ Compact ]
[ Version ( since = "2.32" ) ]
[ CCode ( ref_function = "g_thread_ref" , type_id = "G_TYPE_THREAD" , unref_function = "g_thread_unref" ) ]
public class Thread<T>
[ Version ( since = "2.32" ) ]
[ CCode ( ref_function = "g_thread_ref" , type_id = "G_TYPE_THREAD" , unref_function = "g_thread_unref" ) ]
public class Thread<T>
The Thread struct represents a running thread.
This struct is returned by Thread or Thread.try. You can obtain the Thread struct representing the current thread by calling self.
GThread is refcounted, see g_thread_ref
and g_thread_unref
. The thread represented by it holds a reference while it
is running, and join consumes the reference that it is given, so it is normally not
necessary to manage GThread references explicitly.
The structure is opaque -- none of its fields may be directly accessed.
Example: Threads:
public class MyThread : Object {
public int x_times { get; private set; }
public MyThread (int times) {
this.x_times = times;
}
public int run () {
for (int i = 0; i < this.x_times; i++) {
print ("ping! %d/%d\n", i + 1, this.x_times);
Thread.usleep (10000);
}
// return & exit have the same effect
Thread.exit (42);
return 43;
}
}
public static int main (string[] args) {
// Check whether threads are supported:
if (Thread.supported () == false) {
stderr.printf ("Threads are not supported!\n");
return -1;
}
try {
// Start a thread:
MyThread my_thread = new MyThread (10);
Thread<int> thread = new Thread<int>.try ("My fst. thread", my_thread.run);
// Wait until thread finishes:
int result = thread.join ();
// Output: `Thread stopped! Return value: 42`
print ("Thread stopped! Return value: %d\n", result);
} catch (Error e) {
print ("Error: %s\n", e.message);
}
return 0;
}
valac --target-glib 2.32 --pkg glib-2.0 GLib.Thread.vala
Namespace: GLib
Package: glib-2.0