123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131 |
- alias uint8 = ubyte;
- import std.stdio;
- import std.concurrency : receive, send, spawn, thisTid, Tid;
- import core.time : Duration, dur;
- import core.thread : Thread;
- Tid[4] workers_tids;
- struct Msg1{
- uint8 command;
- }
- struct Msg2{
- Tid sender;
- string client_id;
- }
- struct Msg21{
- uint8 command;
- string client_id;
- }
- struct Msg3{
- Tid sender;
- uint8 command;
- string client_id;
- }
- void test2_worker(uint8 n){
- writeln("started worker = ", n);
-
- while(true){
- //Thread.sleep(dur!"seconds"(120));
- receive(
- (Msg1 m) => writeln("got Msg1: command = ", m.command),
- (Msg2 m) => writeln("got Msg2: from ", m.sender, ", client_id = ", m.client_id),
- (Msg21 m) => writeln("got Msg21: command = ", m.command, ", client_id = ", m.client_id),
- (Msg3 m) => writeln("got Msg3: from ", m.sender, ", command ", m.command)
- );
- }
- writeln("stopped worker = ", n); // unreachable
- }
- void test2_ticker(){
- writeln("started ticker");
-
- while(true){
- Thread.sleep(dur!"seconds"(5));
- writeln("tick (5 seconds passed)");
- }
- }
- void test2_spawner(){
- spawn(&test2_ticker);
-
- uint8 i = 4;
-
- while(i > 0){
- workers_tids[i - 1] = spawn(&test2_worker, i);
-
- i--;
- }
-
- Thread.sleep(dur!"seconds"(30));
-
- send(workers_tids[0], Msg1(42)); // async command ?
- send(workers_tids[1], Msg2(thisTid, "client_123"));
- send(workers_tids[2], Msg21(5, "client_456"));
- send(workers_tids[3], Msg3(thisTid, 99, "client_789"));
-
- Thread.sleep(dur!"seconds"(20));
-
- writeln("the end");
- }
- /*
- // message passing - async send
- > make run
- ./vtest2
- started worker = 2
- started worker = 1
- started ticker
- started worker = 3
- started worker = 4
- tick (5 seconds passed)
- tick (5 seconds passed)
- tick (5 seconds passed)
- tick (5 seconds passed)
- tick (5 seconds passed)
- got Msg1: command = 42
- got Msg3: from Tid(7f8a8dcc38f0), command 99
- got Msg21: command = 5, client_id = client_456
- got Msg2: from Tid(7f8a8dcc38f0), client_id = client_123
- tick (5 seconds passed)
- tick (5 seconds passed)
- tick (5 seconds passed)
- tick (5 seconds passed)
- the end
- tick (5 seconds passed)
- tick (5 seconds passed)
- tick (5 seconds passed)
- tick (5 seconds passed)
- tick (5 seconds passed)
- tick (5 seconds passed)
- tick (5 seconds passed)
- tick (5 seconds passed)
- tick (5 seconds passed)
- tick (5 seconds passed)
- tick (5 seconds passed)
- tick (5 seconds passed)
- tick (5 seconds passed)
- tick (5 seconds passed)
- tick (5 seconds passed)
- hello here!
- tick (5 seconds passed)
- tick (5 seconds passed)
- tick (5 seconds passed)
- ...
- */
|