Advertisement
Guest User

parallel dag traversal in D

a guest
Oct 22nd, 2013
197
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
D 1.57 KB | None | 0 0
  1. import std.stdio;
  2. import std.conv;
  3. import std.parallelism;
  4.  
  5. class Node {
  6.     string name;
  7.     Node[] clients;
  8.     Node[] masters;
  9.     bool dirty = true;
  10.  
  11.     this(string inname){
  12.         this.name = inname;
  13.     }
  14.  
  15.     void doProcess(){
  16.         writeln("Cleaning ", this.name);
  17.         this.dirty = false;
  18.     }
  19.  
  20.     override string toString() const {
  21.         return name;
  22.     }
  23.  
  24.     void addMasters(Node[] inmasters ...){
  25.         this.masters ~= inmasters;
  26.         foreach (master; inmasters){
  27.             master.clients ~= this;
  28.         }
  29.     }
  30.  
  31.     bool canProcess() const {
  32.         foreach (node; this.masters){
  33.             if (node.dirty){
  34.                 return false;
  35.             }
  36.         }
  37.         return true;
  38.     }
  39. }
  40.  
  41. Node[] mkLinearDag(const int depth){
  42.     // makes a simple linked list of named nodes
  43.     Node[] nodes;    
  44.     auto root = new Node("RootNode");
  45.     nodes ~= root;
  46.     foreach (i; 0 .. depth){
  47.         nodes ~= new Node("test" ~ to!string(i));
  48.         nodes[$-1].addMasters(nodes[$-2]);
  49.     }
  50.     return nodes;
  51. }
  52.  
  53. void cleanNodeSimple(Node node, TaskPool pool){
  54.     node.doProcess();
  55.     foreach (cli; node.clients){
  56.         if (cli.canProcess()){
  57.             pool.put( task!cleanNodeSimple(cli, pool) );
  58.         }
  59.     }
  60. }
  61.  
  62. void main(){
  63.     auto dag = mkLinearDag(5);
  64.     auto pool = taskPool();
  65.  
  66.     pool.put( task!cleanNodeSimple(dag[0], pool));
  67.     pool.finish(true);
  68.  
  69.     writeln("\n\nOutput:");
  70.     foreach (d;dag){
  71.         writeln(d);
  72.         writeln(d.dirty ? "dirty" : "clean","\n");
  73.     }
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement