2016-12-05 89 views
1

我最近開始使用Haxe Process類。我用它來調用curl命令。正如您所期望的那樣,進程將阻止程序直到完成。類似於在Haxe中同時運行多個Process的最佳方式是什麼?

for(obj in array) { 
var curl = 'curl "http://something.com?param=$obj"'; 
var process = new Process(curl); 
trace('finished); 
process.close(); 

} 

我想要做的是跑起來一次說4或5個進程。如果我基本上可以創建一個for循環,其中有100個條目並且一次運行多達4個進程,直到我們到達數組的末尾,那將是非常棒的。

回答

1

我想你需要看看線程。我發現這個例子可以幫助,但不知道你在HAXE/Java的

#if cpp 
    import cpp.vm.Thread; 
    import cpp.vm.Deque; 
#elseif neko 
    import neko.vm.Thread; 
    import neko.vm.Deque; 
#end 

/** 
A simple Haxe class for easily running threads and calling functions on the primary thread. 
from https://github.com/underscorediscovery/ 
*/ 
class Runner { 

    public static var primary : Thread; 

    static var queue : Deque<Void->Void>; 

     /** Call this on your thread to make primary, 
      the calling thread will be used for callbacks. */ 
    public static function init() { 
     queue = new Deque<Void->Void>(); 
     primary = Thread.current(); 
    } 

     /** Call this on the primary manually, 
      Returns the number of callbacks called. */ 
    public static function run() : Int { 

     var more = true; 
     var count = 0; 

     while(more) { 
      var item = queue.pop(false); 
      if(item != null) { 
       count++; item(); item = null; 
      } else { 
       more = false; break; 
      } 
     } 

     return count; 

    } //process 

     /** Call a function on the primary thread without waiting or blocking. 
      If you want return values see call_primary_ret */ 
    public static function call_primary(_fn:Void->Void) { 

     queue.push(_fn); 

    } //call_primary 

     /** Call a function on the primary thread and wait for the return value. 
      This will block the calling thread for a maximum of _timeout, default to 0.1s. 
      To call without a return or blocking, use call_primary */ 
    public static function call_primary_ret<T>(_fn:Void->T, _timeout:Float=0.1) : Null<T> { 

     var res:T = null; 
     var start = haxe.Timer.stamp(); 
     var lock = new cpp.vm.Lock(); 

      //add to main to call this 
     queue.push(function() { 
      res = _fn(); 
      lock.release(); 
     }); 

      //wait for the lock release or timeout 
     lock.wait(_timeout); 

      //clean up 
     lock = null; 
      //return result 
     return res; 

    } //call_primary_ret 

     /** Create a thread using the given function */ 
    public static function thread(fn:Void->Void) : Thread { 
     return Thread.create(fn); 
    } 

} //Runner 

來源方式是:https://gist.github.com/underscorediscovery/e66e72ec702bdcedf5af45f8f4712109

相關問題