Re: [Vala] Threads and closures problem



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); };
                        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();
                h.run();
                h.run(); // Another thread
                loop.run();
                return 0;
        }
}

// valac --thread hhh.vala

I get:

$./hhh
in thread : test 
in thread : (null) 

Ideas?
Regards,
Jörn

PS: Sorry for double post, but I forgot the list

Am Donnerstag, den 14.01.2010, 00:38 +0100 schrieb Łukasz Pankowski:
JM <interflug1 gmx net> writes:

Hi all
I just played around with closures as thread functions. I'm not sure if
this example is supposed to work, but at least it compiles.


class HHH : Object {
    public void run() {
            string test = "test";
            try {
                    Thread.create( ()=> { print("in thread : %s \n", test); }, false);

Hi

if you look into a hhh.c generated with

valac -C --thread hhh.vala

you can see that the clause data is destroyed at the end of HHH.run
(hhh_run in C) as the closure function is no longer referenced when
exiting HHH.run, you have to assign the closure to a variable to keep
it alive, for example

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

it gives a compilation warning but works (I needed to add usleep to observe your problem)

$ valac --thread --pkg posix temp.vala
hhh.vala.c: In function ‘hhh_run’:
hhh.vala.c:111: warning: assignment from incompatible pointer type


Anybody knows how this should be handled?
Regards
Jörn





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