1 /+ dub.json: 2 { 3 "authors": [ 4 "Dmitry Olshansky" 5 ], 6 "copyright": "Copyright © 2024, Dmitry Olshansky", 7 "dependencies": { 8 "photon": { "path": ".." } 9 }, 10 "description": "A test for channels API", 11 "license": "BOOST", 12 "name": "channels" 13 } 14 +/ 15 module examples.channels; 16 17 import std.algorithm, std.datetime, std.range, std.stdio; 18 import photon; 19 20 void first(shared Channel!string work, shared Channel!int completion) { 21 delay(2.msecs); 22 work.put("first #1"); 23 delay(2.msecs); 24 work.put("first #2"); 25 delay(2.msecs); 26 work.put("first #3"); 27 completion.put(1); 28 } 29 30 void second(shared Channel!string work, shared Channel!int completion) { 31 delay(3.msecs); 32 work.put("second #1"); 33 delay(3.msecs); 34 work.put("second #2"); 35 completion.put(2); 36 } 37 38 void main() { 39 startloop(); 40 auto jobQueue = channel!string(2); 41 auto finishQueue = channel!int(1); 42 go({ 43 first(jobQueue, finishQueue); 44 }); 45 go({ // producer # 2 46 second(jobQueue, finishQueue); 47 }); 48 go({ // consumer 49 foreach (item; jobQueue) { 50 delay(1.seconds); 51 writeln(item); 52 } 53 }); 54 go({ // closer 55 auto completions = finishQueue.take(2).array; 56 assert(completions.length == 2); 57 jobQueue.close(); // all producers are done 58 }); 59 runFibers(); 60 } 61