Menu

Extended for and threads

Ross
2006-08-09
2013-05-02
  • Ross

    Ross - 2006-08-09

    I am a Nice beginner, so I don't know if this has been discussed before, but I found some unexpected behavior involving the extended for loop and threads last night. Here's an example:

    package loopBug;

    void main(String[] args){
      for(String current : ["one","two","three"])
        new SomeThread( action: ()=>{ println(current); } ).start();
    }

    class SomeThread extends Thread{
      void->void action;
      run(){
        for(int n=0;n!=5;n++)
          {
        action();
        Thread.sleep(100);
          }
      }
    }

    The anonymous method sent to SomeThread runs in the same scope as the for loop, with the result that it changes with every iteration; after the loop finishes, all the threads are running the action of the last iteration.

    Does that seem odd to anyone else?

    It is fairly easy to fix, by making another function that builds a void->void function:

    <T> void->void bind(T->void func,T param)=()=>{func(param);};

     
    • Artem Grinblat

      Artem Grinblat - 2006-08-10

      Yes, that is to be expected from a Nice closure.
      In Java you can pass only read-only (final) variables to the closure, but in Nice you can access and modify any context variables from a closure.

       
    • Artem Grinblat

      Artem Grinblat - 2006-08-10

      In some functional languages this is deliberately used as a primary way to communicate between threads. One example, if i'm not mistaken, is the Felix Language. http://felix.sourceforge.net/

       

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.