I want to create a thread-safe singleton instance for my vala class.
As you know, singletons may lead to threading issues if not properly implemented.
Also you can use SingleInstance Code Attribute. It does the same for you automatically!
[SingleInstance]
public class ExampleClass : Object {
    public int prop { get; set; default = 42; }
    public ExampleClass () {
        // ...
    }
}
int main (string[] args) {
    var a = new ExampleClass (); // the two refs
    var b = new ExampleClass (); // are the same
    b.prop += 1;
    assert (a.prop == b.prop);
    return 0;
}
Note, that in this case you don't need to call a static function like instance() or get_instance(). Simply creating an object via new will give you a reference to the singleton.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With