Re: [Vala] Threads and closures problem



On Thu, January 14, 2010 21:22, JM wrote:
Looks like closures and threads are incompatible right now.

I came across exactly the same issue when trying to pass a parameter
to a thread.  The problem is to maintain a reference to the closure
which can be released when the closure is no longer needed.  This is
the best work-around I've found so far, but it involves creating a
circular reference loop:

   private static class BoxedThreadFunc<T> {
      public ThreadFunc<T>? run;
   }

   [...]

      // 'param' is the value I want to pass to the thread
      var param = [...];
      BoxedThreadFunc<void*> btf = new BoxedThreadFunc<void*>();
      btf.run = () => {
         process(param);
         var tmp = (owned) btf; tmp.run = null;   // Cleanup
         return null;
      };
      try {
         Thread.create<void*>(btf.run, false);
      } catch (ThreadError e) {
         btf.run = null;   // Cleanup
         [...]
      }

So 'btf' keeps the reference to the closure alive, as it is itself
referenced by the closure (circular ref loop).  In theory 'btf.run =
null' should destroy both 'btf' and the closure, but in that case the
C code tries to reference through the now-destroyed closure and causes
a segfault, which is why this code goes via 'tmp' within the closure.
Hopefully I'm not breaking any rules.

Jim

-- 
 Jim Peters                  (_)/=\~/_(_)                 jim uazu net
                          (_)  /=\  ~/_  (_)
 UazĂș                  (_)    /=\    ~/_    (_)                http://
 in Peru            (_) ____ /=\ ____ ~/_ ____ (_)            uazu.net



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