Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a thread safe singleton in vala?

Tags:

glib

vala

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.

like image 387
Name is carl Avatar asked Oct 28 '25 08:10

Name is carl


1 Answers

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.

like image 144
5 revs Avatar answered Oct 30 '25 12:10

5 revs