/
go.d
621 lines (494 loc) · 13.1 KB
/
go.d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
module jin.go;
import core.atomic;
import core.time;
import std.stdio;
import std.range;
import std.exception;
import std.typecons;
import std.traits;
import std.algorithm;
import des.ts;
public import vibe.core.core;
public import vibe.core.concurrency;
/// vibe.core.core.yield works not correctly
alias yield = vibe.core.concurrency.yield;
/// Run function asynchronously
auto go( alias task , Args... ) ( auto ref Args args )
if( is( ReturnType!task : void ) && ( Parameters!task.length == Args.length ) )
{
return runWorkerTaskH( &task , args );
}
/// Run function asynchronously and return channel connectetd with range returned by function
auto go( alias task , Args... ) ( auto ref Args args )
if( isInputRange!(ReturnType!task) )
{
alias Result = ReturnType!task;
alias Value = ElementType!Result;
auto future = new Channel!Value;
runWorkerTask( ( Channel!Value future , Result function( Args ) task , Args args ) {
foreach( value ; task( args ) ) future.next = value;
future.close();
} , future , &task , args );
return future;
}
/// Run function with autocreated result channel and return this channel
auto go( alias task , Args... )( auto ref Args args )
if( ( Parameters!task.length == Args.length + 1 )&&( is( Parameters!task[0] == Channel!Message , Message ) ) )
{
alias Future = Parameters!task[0];
auto future = new Future;
go!task( future , args );
return future;
}
/// Cut and return head from input range;
auto next( Range )( auto ref Range range )
if( isInputRange!Range )
{
auto value = range.front;
range.popFront;
return value;
}
/// Put to output range
auto next( Range , Value )( auto ref Range range , Value value )
if( isOutputRange!(Range,Value) )
{
return range.put( value );
}
/// Wait-free one input one output queue
class Channel( Message )
{
/// Allow transferring between tasks
static __isIsolatedType = true;
/// Message needs for receiver
bool needed;
/// Offset of first not received message
private size_t tail;
/// Cyclic buffer of transferring messages
private Message[] messages;
/// Offset of next free slot for message
private size_t head;
/// One of two task will no longer operate with this channel
bool closed;
/// Limit channel to 1KB by default
this( int size = 1000 / Message.sizeof - 1 )
{
enforce( size > 0 , "Channel size must be greater then 0" );
this.messages = new Message[ size + 1 ];
}
/// Maximum transferring messages count at one time
size_t size( )
{
return this.messages.length - 1;
}
/// No more messages in buffer
bool clear( )
{
return this.tail == this.head;
}
/// End of input range
auto empty( )
{
return this.clear && this.closed;
}
/// No more messages can be transferred now
bool full( )
{
return this.tail == ( this.head + 1 ) % this.messages.length;
}
/// Count of messages in buffer now
auto pending( )
{
return ( this.head - this.tail ) % this.messages.length;
}
/// Count of messages that can be sended before buffer will be full
auto available( )
{
return this.size - this.pending;
}
/// Inform other task about disconnecting
/// TODO: deprecate by unique refs
void close( )
{
this.closed = true;
}
/// Put message to head
Value put( Value )( Value value )
{
static assert( isWeaklyIsolated!Value , "Argument type " ~ Value.stringof ~ " is not safe to pass between threads." );
//enforce( !this.closed , "Channel is closed" );
while( this.full ) yield;
this.needed = false;
this.messages[ this.head ] = value;
atomicFence;
this.head = ( this.head + 1 ) % this.messages.length;
return value;
}
/// Create and put message to head
Value put( Value , Args... )( Args args )
{
return this.put( Value( args ) );
}
/// Get message at tail
auto front( )
{
if( this.clear ) this.needed = true;
while( this.clear ) {
enforce( !empty , "Channel is closed" );
yield;
}
return this.messages[ this.tail ];
}
/// Remove message from tail
auto popFront( )
{
enforce( !this.clear , "Channel is clear" );
this.tail = ( this.tail + 1 ) % this.messages.length;
}
}
/// Common channel collections realization
mixin template Channels( Message )
{
/// All registered channels
Channel!Message[] channels;
/// Offset of current channel
private size_t current;
/// Make new registered channel
auto make( Args... ) ( Args args )
{
auto channel = new Channel!Message( args );
this.channels ~= channel;
return channel;
}
/// Close all channels;
void close( )
{
foreach( channel ; this.channels ) channel.close();
}
}
/// Round robin input channels
struct Inputs( Message )
{
mixin Channels!Message;
/// No more messages in all channels
auto clear( )
{
if( !this.channels.length ) return true;
auto start = this.current;
do {
auto channel = this.channels[ this.current ];
if( !channel.clear ) return false;
this.current = ( this.current + 1 ) % this.channels.length;
} while( this.current != start );
return true;
}
/// End of input range
auto empty( )
{
if( !this.channels.length ) return true;
auto start = this.current;
do {
auto channel = this.channels[ this.current ];
if( !channel.empty ) return false;
this.current = ( this.current + 1 ) % this.channels.length;
} while( this.current != start );
return true;
}
/// Get message at tail of current non clear channel or wait
auto front( )
{
while( this.clear ) yield;
return this.channels[ this.current ].front;
}
/// Remove message from tail of current channel and switch to another channel
void popFront( )
{
this.channels[ this.current ].popFront;
this.current = ( this.current + 1 ) % this.channels.length;
}
}
/// Round robin output channels
struct Outputs( Message )
{
mixin Channels!Message;
/// No more messages can be transferred now
auto full( )
{
if( !this.channels.length ) return true;
auto start = this.current;
do {
auto channel = this.channels[ this.current ];
if( !channel.full ) return false;
this.current = ( this.current + 1 ) % this.channels.length;
} while( this.current != start );
return true;
}
/// Put message to current non full channel and switch channel
Value put( Value )( Value value )
{
while( this.full ) yield;
auto message = this.channels[ this.current ].put( value );
this.current = ( this.current + 1 ) % this.channels.length;
return message;
}
}
/// Bidirection : start , put*2 , take
unittest
{
static void summing( Channel!int output , Channel!int input ) {
output.next = input.next + input.next;
output.close();
}
auto output = new Channel!int;
auto input = go!summing( output );
output.next = 3;
output.next = 4;
input.next.assertEq( 3 + 4 );
}
/// Bidirection : put*2 , start , take
unittest
{
static void summing( Channel!int output , Channel!int input ) {
output.next = input.next + input.next;
output.close();
}
auto output = new Channel!int;
output.next = 3;
output.next = 4;
auto input = go!summing( output );
input.next.assertEq( 3 + 4 );
}
/// Round robin : start*2 , put*4 , take*2
unittest
{
Outputs!int output;
Inputs!int input;
static void summing( Channel!int output , Channel!int input ) {
output.next = input.next + input.next;
output.close();
}
go!summing( input.make , output.make );
go!summing( input.make , output.make );
output.next = 3; // 1
output.next = 4; // 2
output.next = 5; // 1
output.next = 6; // 2
input.array.sort().assertEq([ 3 + 5 , 4 + 6 ]);
}
/// Event loop on multiple queues
unittest
{
static void generating1( Channel!int output ) {
output.next = 2;
output.next = 3;
output.close();
}
static void generating2( Channel!long output ) {
output.next = 4;
output.next = 5;
output.close();
}
auto input1 = go!generating1;
auto input2 = go!generating2;
int[] results1;
long[] results2;
while( !input1.empty || !input2.empty ) {
if( !input1.clear ) results1 ~= input1.next;
if( !input2.clear ) results2 ~= input2.next;
}
results1.assertEq([ 2 , 3 ]);
results2.assertEq([ 4 , 5 ]);
}
/// Blocking on buffer overflow
unittest
{
static void summing( Channel!int output ) {
foreach( i ; ( output.size * 2 ).iota ) {
output.next = 1;
}
output.close();
}
auto input = go!summing;
while( !input.full ) yield;
input.sum.assertEq( input.size * 2 );
}
debug( demo )
{
/// https://tour.golang.org/concurrency/1
/// "go" template starts function in new asynchronous coroutine
/// Coroutines starts in thread pool and may be executed in parallel threads.
/// Only thread safe values can be passed to function.
unittest
{
import core.time;
import jin.go;
__gshared static string[] log;
static void saying( string message )
{
for( int i = 0 ; i < 3 ; ++i ) {
sleep( 100.msecs );
log ~= message;
}
}
go!saying( "hello" );
sleep( 50.msecs );
saying( "world" );
log.assertEq([ "hello" , "world" , "hello" , "world" , "hello" , "world" ]);
}
/// https://tour.golang.org/concurrency/3
/// Channel is one-consumer-one-provider wait-free typed queue with InputRange and OutputRange interfaces support.
/// Use "next" property to send and receive messages;
unittest
{
import jin.go;
auto numbers = new Channel!int(2);
numbers.next = 1;
numbers.next = 2;
assert( numbers.next == 1 );
assert( numbers.next == 2 );
}
/// https://tour.golang.org/concurrency/2
/// Inputs is round robin input channel list with InputRange and Channel interfaces support.
/// Method "make" creates new channel for every coroutine
unittest
{
import std.algorithm;
import std.range;
import jin.go;
static auto summing( Channel!int sums , const int[] numbers ) {
sums.next = numbers.sum;
}
immutable int[] numbers = [ 7 , 2 , 8 , -9 , 4 , 0 ];
Inputs!int sums;
go!summing( sums.make , numbers[ 0 .. $/2 ] );
go!summing( sums.make , numbers[ $/2 .. $ ] );
auto res = sums.take(2).array;
res.assertEq([ 17 , -5 ]);
}
/// https://tour.golang.org/concurrency/4
/// You can iterate over channel by "foreach" like InputRange, and all standart algorithms support this.
/// Use "close" method to notify about no more data.
unittest
{
import std.range;
import jin.go;
static auto fibonacci( Channel!int numbers , int count )
{
auto range = recurrence!q{ a[n-1] + a[n-2] }( 0 , 1 ).take( count );
foreach( x ; range ) numbers.next = x;
numbers.close();
}
auto numbers = new Channel!int(10);
go!fibonacci( numbers , numbers.size );
numbers.array.assertEq([ 0 , 1 , 1 , 2 , 3 , 5 , 8 , 13 , 21 , 34 ]);
}
/// https://tour.golang.org/concurrency/4
/// Function can return InputRange and it will be automatically converted to input channel.
unittest
{
import std.range;
import jin.go;
static auto fibonacci( int limit )
{
return recurrence!q{ a[n-1] + a[n-2] }( 0 , 1 ).take( limit );
}
fibonacci( 10 ).array.assertEq([ 0 , 1 , 1 , 2 , 3 , 5 , 8 , 13 , 21 , 34 ]);
go!fibonacci( 10 ).array.assertEq([ 0 , 1 , 1 , 2 , 3 , 5 , 8 , 13 , 21 , 34 ]);
}
/// https://tour.golang.org/concurrency/5
/// Use custom loop to watch multiple channels as you want.
/// Provider can be slave by using "needed" property.
/// Use "yield" to allow other coroutines executed between cycles.
unittest
{
import std.range;
import jin.go;
__gshared int[] log;
static auto fibonacci( Channel!int numbers , Channel!bool control )
{
auto range = recurrence!q{ a[n-1] + a[n-2] }( 0 , 1 );
while( !control.closed )
{
if( numbers.needed ) numbers.next = range.next;
yield;
}
log ~= -1;
numbers.close();
}
static void print( Channel!bool control , Channel!int numbers )
{
foreach( i ; 10.iota ) log ~= numbers.next;
control.close();
}
auto numbers = new Channel!int(1);
auto control = new Channel!bool(1);
go!print( control , numbers );
go!fibonacci( numbers , control );
while( !control.empty || !numbers.empty ) yield;
log.assertEq([ 0 , 1 , 1 , 2 , 3 , 5 , 8 , 13 , 21 , 34 , -1 ]);
}
/// https://tour.golang.org/concurrency/6
/// You can ommit first argument of Channel type, and it will be autogenerated and returned.
unittest
{
import core.time;
import jin.go;
static auto after( Channel!bool channel , Duration dur )
{
sleep( dur );
if( !channel.closed ) channel.next = true;
}
static auto tick( Channel!bool channel , Duration dur )
{
while( !channel.closed ) after( channel , dur );
}
auto ticks = go!tick( 101.msecs );
auto booms = go!after( 501.msecs );
string log;
while( booms.clear )
{
while( !ticks.clear ) {
log ~= "tick";
ticks.popFront;
}
log ~= ".";
sleep( 51.msecs );
}
log ~= "BOOM!";
log.assertEq( "..tick..tick..tick..tick..BOOM!" );
}
/// https://tour.golang.org/concurrency/9
unittest
{
import core.atomic;
import core.time;
import std.range;
import std.typecons;
import jin.go;
synchronized class SafeCounter
{
private int[string] store;
void inc( string key )
{
++ store[key];
}
auto opIndex( string key )
{
return store[ key ];
}
void opIndexUnary( string op = "++" )( string key )
{
this.inc( key );
}
}
scope static counter = new shared SafeCounter;
static void working( int i )
{
++ counter["somekey"];
}
foreach( i ; 1000.iota ) {
go!working( i );
}
sleep( 1.seconds );
counter["somekey"].assertEq( 1000 );
}
}