Re: [Vala] Threads and closures problem

On Thu, January 14, 2010 01:12, JM wrote:
Hi Łukas
Thanks for your reply! This somehow does not work as soon as I add
another thread.

class HHH : Object {
        private ThreadFunc f;
        public void run() {
                string test = "test";
                try {
                        f = ()=> { print("in thread : %s \n", test); };

When you call this second time, you *replace* the closure created the
first time around, causing it to be deleted. Than it's memory probably
gets reused when creating the thread (in the first post you didn't do
any allocation after the thread was created, so there was nothing to
overwrite the data), causing the first thread to fail.

You need to have one variable for each closure you create, or a collection
of them. Note, that delegates are not compatible with generics, but you can
wrap them in class instances and those are. I don't know whether explicit
boxing (append ? to the type - does the trick with double and struct types)
is supported for delegates or not.

                        Thread.create(f, false);
                catch(GLib.ThreadError e) {
                        print("%s", e.message);

        public static MainLoop loop;

        public static int main() {
                loop = new MainLoop(null, false);
                var h = new HHH();
      ; // Another thread
                return 0;

// valac --thread hhh.vala

I get:

in thread : test
in thread : (null)


                                        - Jan Hudec <bulb ucw cz>

[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]