forked from MacRuby/MacRuby
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgcd.c
1495 lines (1335 loc) · 45.5 KB
/
gcd.c
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
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* MacRuby API for Grand Central Dispatch.
*
* This file is covered by the Ruby license. See COPYING for more details.
*
* Copyright (C) 2012, The MacRuby Team. All rights reserved.
* Copyright (C) 2009-2011, Apple Inc. All rights reserved.
*/
#define GCD_BLOCKS_COPY_DVARS 1
#include "macruby_internal.h"
#include "gcd.h"
#include <unistd.h>
#include "ruby/intern.h"
#include "ruby/node.h"
#include "ruby/io.h"
#include "objc.h"
#include "id.h"
#include "vm.h"
#include <libkern/OSAtomic.h>
#include <asl.h>
static SEL selClose;
typedef struct {
struct RBasic basic;
int suspension_count;
dispatch_object_t obj;
} rb_dispatch_obj_t;
#define RDispatch(val) ((rb_dispatch_obj_t*)val)
typedef struct {
struct RBasic basic;
int suspension_count;
dispatch_queue_t queue;
int should_release_queue;
} rb_queue_t;
#define RQueue(val) ((rb_queue_t*)val)
typedef struct {
struct RBasic basic;
int suspension_count;
dispatch_group_t group;
} rb_group_t;
#define RGroup(val) ((rb_group_t*)val)
typedef enum SOURCE_TYPE_ENUM
{
SOURCE_TYPE_DATA_ADD,
SOURCE_TYPE_DATA_OR,
SOURCE_TYPE_MACH_SEND,
SOURCE_TYPE_MACH_RECV,
SOURCE_TYPE_PROC,
SOURCE_TYPE_READ,
SOURCE_TYPE_SIGNAL,
SOURCE_TYPE_TIMER,
SOURCE_TYPE_VNODE,
SOURCE_TYPE_WRITE
} source_enum_t;
typedef struct {
struct RBasic basic;
int suspension_count;
dispatch_source_t source;
source_enum_t source_enum;
rb_vm_block_t *event_handler;
VALUE handle;
} rb_source_t;
#define RSource(val) ((rb_source_t*)val)
typedef struct {
struct RBasic basic;
int reserved;
dispatch_semaphore_t sem;
long count;
} rb_semaphore_t;
#define RSemaphore(val) ((rb_semaphore_t*)val)
static OSSpinLock _suspensionLock = 0;
static VALUE mDispatch;
static VALUE cObject;
static void *
dispatch_object_imp(void *rcv, SEL sel)
{
rb_dispatch_obj_t *obj = RDispatch(rcv);
return (void *)obj->obj._do;
}
// queue stuff
static VALUE cQueue;
static VALUE qMain;
static VALUE qHighPriority;
static VALUE qDefaultPriority;
static VALUE qLowPriority;
static ID high_priority_id;
static ID low_priority_id;
static ID default_priority_id;
#if MAC_OS_X_VERSION_MAX_ALLOWED >= 1070
static VALUE qBackgroundPriority;
static ID background_priority_id;
#endif
static VALUE cGroup;
static VALUE cSource;
static VALUE cSemaphore;
static VALUE const_time_now;
static VALUE const_time_forever;
static inline void
Check_Queue(VALUE object)
{
if (CLASS_OF(object) != cQueue && object != qMain) {
rb_raise(rb_eArgError, "expected Queue object, but got %s",
rb_class2name(CLASS_OF(object)));
}
}
dispatch_queue_t
rb_get_dispatch_queue_object(VALUE queue)
{
Check_Queue(queue);
return (dispatch_queue_t)dispatch_object_imp((void *)queue, 0);
}
static inline void
Check_Group(VALUE object)
{
if (CLASS_OF(object) != cGroup) {
rb_raise(rb_eArgError, "expected Group object, but got %s",
rb_class2name(CLASS_OF(object)));
}
}
static VALUE
rb_raise_init(VALUE self, SEL sel)
{
rb_raise(rb_eArgError, "initializer called without any arguments");
return self;
}
#define SEC2NSEC_UINT64(sec) (uint64_t)(sec * NSEC_PER_SEC)
#define SEC2NSEC_INT64(sec) (int64_t)(sec * NSEC_PER_SEC)
#define TIMEOUT_MAX (1.0 * INT64_MAX / NSEC_PER_SEC)
static inline uint64_t
rb_num2nsec(VALUE num)
{
if (num == const_time_forever) {
return DISPATCH_TIME_FOREVER;
}
const double sec = rb_num2dbl(num);
if (sec < 0.0) {
rb_raise(rb_eArgError, "negative delay specified");
}
return SEC2NSEC_UINT64(sec);
}
static inline dispatch_time_t
rb_num2timeout(VALUE num)
{
dispatch_time_t dispatch_timeout = DISPATCH_TIME_FOREVER;
if (!NIL_P(num)) {
const double sec = rb_num2dbl(num);
if (sec < TIMEOUT_MAX) {
dispatch_timeout = dispatch_walltime(NULL, SEC2NSEC_INT64(sec));
}
}
return dispatch_timeout;
}
static VALUE
rb_queue_alloc(VALUE klass, SEL sel)
{
NEWOBJ(queue, rb_queue_t);
OBJSETUP(queue, klass, RUBY_T_NATIVE);
queue->suspension_count = 0;
queue->should_release_queue = 0;
return (VALUE)queue;
}
static VALUE
rb_queue_from_dispatch(dispatch_queue_t dq, bool should_retain)
{
VALUE q = rb_queue_alloc(cQueue, 0);
if (should_retain) {
GC_RETAIN(q);
}
RQueue(q)->queue = dq;
return q;
}
/*
* call-seq:
* Dispatch::Queue.concurrent(priority=:default) => Dispatch::Queue
*
* Returns one of the global concurrent priority queues.
*
* A dispatch queue is a FIFO queue that accepts tasks in the form of a block.
* Blocks submitted to dispatch queues are executed on a pool of threads fully
* managed by the system. Dispatched tasks execute one at a time in FIFO order.
* GCD takes take of using multiple cores effectively and better accommodate
* the needs of all running applications, matching them to the
* available system resources in a balanced fashion.
*
* Use concurrent queues to execute large numbers of tasks concurrently.
* GCD automatically creates three concurrent dispatch queues that are global
* to your application and are differentiated only by their priority level.
*
* The three priority levels are: +:low+, +:default+,
* +:high+, corresponding to the DISPATCH_QUEUE_PRIORITY_HIGH,
* DISPATCH_QUEUE_PRIORITY_DEFAULT, and DISPATCH_QUEUE_PRIORITY_LOW
* (detailed in the dispatch_queue_create(3)[http://developer.apple.com/mac/library/DOCUMENTATION/Darwin/Reference/ManPages/man3/dispatch_queue_create.3.html]
* man page). The GCD thread dispatcher
* will perform actions submitted to the high priority queue before any actions
* submitted to the default or low queues, and will only perform actions on the
* low queues if there are no actions queued on the high or default queues.
* When installed on Mac OS 10.7 or later, the +:background+ priority level is
* available. Actions submitted to this queue will execute on a thread set to
* background state (via setpriority(2)), which throttles disk I/O and sets the
* thread's scheduling priority to the lowest value possible.
*
* On Mac OS 10.7 and later, passing a string to +concurrent+ creates a new
* concurrent queue with the specified string as its label. Private concurrent queues
* created this way are identical to private FIFO queues created with +new+, except
* for the fact that they execute their blocks in parallel.
*
* gcdq = Dispatch::Queue.concurrent(:high)
* 5.times { gcdq.async { print 'foo' } }
* gcdq_2 = Dispatch::Queue.concurrent(:low)
* gcdq_2.sync { print 'bar' } # will always print 'foofoofoofoofoobar'.
*
*/
static VALUE
rb_queue_get_concurrent(VALUE klass, SEL sel, int argc, VALUE *argv)
{
VALUE priority;
rb_scan_args(argc, argv, "01", &priority);
if (!NIL_P(priority)) {
#if MAC_OS_X_VERSION_MAX_ALLOWED >= 1070
if (TYPE(priority) == T_STRING) {
return rb_queue_from_dispatch(
dispatch_queue_create(RSTRING_PTR(priority), DISPATCH_QUEUE_CONCURRENT), 1);
} else if (TYPE(priority) != T_SYMBOL) {
rb_raise(rb_eTypeError, "must pass a symbol or string to `concurrent`");
}
#endif
ID id = rb_to_id(priority);
if (id == high_priority_id) {
return qHighPriority;
}
else if (id == low_priority_id) {
return qLowPriority;
}
#if MAC_OS_X_VERSION_MAX_ALLOWED >= 1070
else if (id == background_priority_id) {
return qBackgroundPriority;
}
#endif
else if (id != default_priority_id) {
rb_raise(rb_eArgError,
"invalid priority `%s' (expected either :low, :default or :high)",
rb_id2name(id));
}
}
return qDefaultPriority;
}
/*
* call-seq:
* Dispatch::Queue.current => Dispatch::Queue
*
* When called from within a block that is being dispatched on a queue,
* this returns the queue in question. If executed outside of a block,
* the result depends on whether the run method has been called on the
* main queue: if it has, it returns the main queue, otherwise it returns
* the default-priority concurrent queue.
*
*/
static VALUE
rb_queue_get_current(VALUE klass, SEL sel)
{
// TODO: check this to see if we need to retain it
return rb_queue_from_dispatch(dispatch_get_current_queue(), false);
}
/*
* call-seq:
* Dispatch::Queue.main => Dispatch::Queue
*
* Returns the dispatch queue for the main thread.
*
*/
static VALUE
rb_queue_get_main(VALUE klass, SEL sel)
{
return qMain;
}
/*
* call-seq:
* Dispatch::Queue.new(label) => Dispatch::Queue
*
* Returns a new serial dispatch queue.
*
* A dispatch is a FIFO queue to which you can submit tasks via a block.
* Blocks submitted to dispatch queues are executed on a pool of threads fully
* managed by the system. Dispatched tasks execute one at a time in FIFO order.
* GCD takes take of using multiple cores effectively to better accommodate
* the needs of all running applications, matching them to the
* available system resources in a balanced fashion.
*
* Use serial GCD queues to ensure that tasks execute in a predictable order.
* It's a good practice to identify a specific purpose for each serial queue,
* such as protecting a resource or synchronizing key processes.
* Create as many as you need - serial queues are extremely lightweight
* (with a total memory footprint of less than 300 bytes); however, remember to
* use concurrent queues if you need to perform idempotent tasks in parallel.
* Dispatch queues need to be labeled and thereofore you need to pass a name
* to create your queue. By convention, labels are in reverse-DNS style.
*
* gcdq = Dispatch::Queue.new('org.macruby.gcd.example')
* gcdq.async { p 'doc' }
* gcdq.async { p 'bar' }
* gcdq.sync {}
*
*/
static VALUE
rb_queue_init(VALUE self, SEL sel, VALUE name)
{
StringValue(name);
rb_queue_t *queue = RQueue(self);
queue->should_release_queue = 1;
queue->queue = dispatch_queue_create(RSTRING_PTR(name), NULL);
assert(queue->queue != NULL);
dispatch_retain(queue->queue);
return self;
}
static IMP rb_queue_finalize_super;
static void
rb_queue_finalize(void *rcv, SEL sel)
{
rb_queue_t *queue = RQueue(rcv);
if (queue->queue != NULL)
{
OSSpinLockLock(&_suspensionLock);
while (queue->suspension_count > 0) {
queue->suspension_count--;
dispatch_resume(queue->queue);
}
if (queue->should_release_queue) {
dispatch_release(queue->queue);
queue->should_release_queue = 0;
}
OSSpinLockUnlock(&_suspensionLock);
}
if (rb_queue_finalize_super != NULL) {
((void(*)(void *, SEL))rb_queue_finalize_super)(rcv, sel);
}
}
static VALUE
rb_block_rescue(VALUE data, VALUE exc)
{
fprintf(stderr, "*** Dispatch block exited prematurely because of an uncaught exception:\n%s\n", rb_str_cstr(rb_format_exception_message(exc)));
return Qnil;
}
static VALUE
rb_block_release_eval(VALUE data)
{
GC_RELEASE(data);
rb_vm_block_t *b = (rb_vm_block_t *)data;
return rb_vm_block_eval(b, 0, NULL);
}
static void
rb_block_dispatcher(void *data)
{
assert(data != NULL);
rb_rescue(rb_block_release_eval, (VALUE)data, rb_block_rescue, Qnil);
}
static rb_vm_block_t *
get_prepared_block()
{
rb_vm_block_t *block = rb_vm_current_block();
if (block == NULL) {
rb_raise(rb_eArgError, "block not given");
}
#if GCD_BLOCKS_COPY_DVARS
block = rb_vm_dup_block(block);
for (int i = 0; i < block->dvars_size; i++) {
VALUE *slot = block->dvars[i];
VALUE *new_slot = xmalloc(sizeof(VALUE));
GC_WB(new_slot, *slot);
GC_WB(&block->dvars[i], new_slot);
}
#else
rb_vm_block_make_detachable_proc(block);
#endif
GC_RETAIN(block);
return block;
}
/*
* call-seq:
* gcdq.async(group=nil) { @i = 42 }
*
* Yields the passed block asynchronously via dispatch_async(3)[http://developer.apple.com/mac/library/DOCUMENTATION/Darwin/Reference/ManPages/man3/dispatch_async.3.html]:
*
* gcdq = Dispatch::Queue.new('doc')
* @i = 0
* gcdq.async { @i = 42 }
* while @i == 0 do; end
* p @i #=> 42
*
* If a group is specified, the dispatch will be associated with that group via
* dispatch_group_async(3)[http://developer.apple.com/mac/library/DOCUMENTATION/Darwin/Reference/ManPages/man3/dispatch_group_async.3.html]:
*
* gcdq = Dispatch::Queue.new('doc')
* gcdg = Dispatch::Group.new
* @i = 3.1415
* gcdq.async(gcdg) { @i = 42 }
* gcdg.wait
* p @i #=> 42
*
*/
static VALUE
rb_queue_dispatch_async(VALUE self, SEL sel, int argc, VALUE *argv)
{
rb_vm_block_t *block = get_prepared_block();
VALUE group;
rb_scan_args(argc, argv, "01", &group);
if (group != Qnil) {
Check_Group(group);
dispatch_group_async_f(RGroup(group)->group, RQueue(self)->queue,
(void *)block, rb_block_dispatcher);
}
else {
dispatch_async_f(RQueue(self)->queue, (void *)block,
rb_block_dispatcher);
}
return Qnil;
}
/*
* call-seq:
* gcdq.sync { @i = 42 }
*
* Yields the passed block synchronously via dispatch_sync(3)[http://developer.apple.com/mac/library/DOCUMENTATION/Darwin/Reference/ManPages/man3/dispatch_sync.3.html]:
*
* gcdq = Dispatch::Queue.new('doc')
* @i = 42
* gcdq.sync { @i = 42 }
* p @i #=> 42
*
*/
static VALUE
rb_queue_dispatch_sync(VALUE self, SEL sel)
{
rb_vm_block_t *block = get_prepared_block();
dispatch_sync_f(RQueue(self)->queue, (void *)block,
rb_block_dispatcher);
return Qnil;
}
/*
* call-seq:
* gcdq.barrier_async { @i = 42 }
*
* This function is a specialized version of the #async dispatch function.
* When a block enqueued with barrier_async reaches the front of a private
* concurrent queue, it waits until all other enqueued blocks to finish executing,
* at which point the block is executed. No blocks submitted after a call to
* barrier_async will be executed until the enqueued block finishes. It returns
* immediately.
*
* If the provided queue is not a concurrent private queue, this function behaves
* identically to the #async function.
*
* This function is only available on OS X 10.7 and later.
*
* gcdq = Dispatch::Queue.concurrent('org.macruby.documentation')
* @i = ""
* gcdq.async { @i += 'a' }
* gcdq.async { @i += 'b' }
* gcdq.barrier_async { @i += 'c' }
* p @i #=> either prints out 'abc' or 'bac'
*
*/
#if MAC_OS_X_VERSION_MAX_ALLOWED >= 1070
static VALUE
rb_queue_dispatch_barrier_async(VALUE self, SEL sel)
{
rb_vm_block_t *block = get_prepared_block();
dispatch_barrier_async_f(RQueue(self)->queue, (void *)block, rb_block_dispatcher);
return Qnil;
}
#endif
/*
* call-seq:
* gcdq.barrier_async { @i = 42 }
*
* This function is identical to the #barrier_async function; however, it blocks
* until the provided block is executed.
*
* If the provided queue is not a concurrent private queue, this function behaves
* identically to the #sync function.
*
* This function is only available on OS X 10.7 and later.
*
* gcdq = Dispatch::Queue.concurrent('org.macruby.documentation')
* @i = ""
* gcdq.async { @i += 'a' }
* gcdq.async { @i += 'b' }
* gcdq.barrier_sync { @i += 'c' } # blocks
* p @i #=> either prints out 'abc' or 'bac'
*
*/
#if MAC_OS_X_VERSION_MAX_ALLOWED >= 1070
static VALUE
rb_queue_dispatch_barrier_sync(VALUE self, SEL sel)
{
rb_vm_block_t *block = get_prepared_block();
dispatch_barrier_sync_f(RQueue(self)->queue, (void *)block, rb_block_dispatcher);
return Qnil;
}
#endif
/*
* call-seq:
* gcdq.after(delay) { block }
*
* Runs the passed block after the given delay (in seconds) using
* dispatch_after(3)[http://developer.apple.com/mac/library/DOCUMENTATION/Darwin/Reference/ManPages/man3/dispatch_after.3.html],
*
* gcdq.after(0.5) { puts 'wait is over :)' }
*
*/
static VALUE
rb_queue_dispatch_after(VALUE self, SEL sel, VALUE delay)
{
dispatch_time_t offset = NIL_P(delay) ? DISPATCH_TIME_NOW : rb_num2timeout(delay);
rb_vm_block_t *block = get_prepared_block();
dispatch_after_f(offset, RQueue(self)->queue, (void *)block,
rb_block_dispatcher);
return Qnil;
}
static VALUE
rb_block_arg_eval(VALUE *args)
{
rb_vm_block_t *b = (rb_vm_block_t *)args[0];
return rb_vm_block_eval(b, 1, &args[1]);
}
static void
rb_block_arg_dispatcher(rb_vm_block_t *block, VALUE param)
{
assert(block != NULL);
VALUE args[2];
args[0] = (VALUE)block;
args[1] = param;
// XXX We are casting a C array to VALUE here!!!
rb_rescue(rb_block_arg_eval, (VALUE)args, rb_block_rescue, Qnil);
}
static void
rb_block_applier(void *data, size_t ii)
{
assert(data != NULL);
rb_vm_block_t *block = rb_vm_uncache_or_dup_block((rb_vm_block_t *)data);
rb_block_arg_dispatcher(block, SIZET2NUM(ii));
}
/*
* call-seq:
* gcdq.apply(count) { |index| block }
*
* Runs a block _count_ number of times asynchronously via
* dispatch_apply(3)[http://developer.apple.com/mac/library/DOCUMENTATION/Darwin/Reference/ManPages/man3/dispatch_apply.3.html],
* passing in an index and waiting until all of them are done.
* You must use a concurrent queue to run the blocks concurrently.
*
* gcdq = Dispatch::Queue.new('doc')
* @result = Array.new(5)
* gcdq.apply(5) {|i| @result[i] = i*i }
* p @result #=> [0, 1, 4, 9, 16]
*
*/
static VALUE
rb_queue_apply(VALUE self, SEL sel, VALUE n)
{
rb_vm_block_t *block = get_prepared_block();
dispatch_apply_f(NUM2SIZET(n), RQueue(self)->queue, (void *)block,
rb_block_applier);
GC_RELEASE(block);
return Qnil;
}
/*
* call-seq:
* gcdq.to_s -> str
*
* Returns the label of the dispatch queue
*
* gcdq = Dispatch::Queue.new('doc')
* gcdq.to_s #=> 'doc'
* gcdq = Dispatch::Queue.main
* gcdq.to_s #=> 'com.apple.main-thread'
*
*/
static VALUE
rb_queue_label(VALUE self, SEL sel)
{
return rb_str_new2(dispatch_queue_get_label(RQueue(self)->queue));
}
static VALUE
rb_main_queue_run(VALUE self, SEL sel)
{
dispatch_main();
return Qnil; // never reached
}
/*
* call-seq:
* obj.suspend!
*
* Suspends the operation of a
* dispatch_object(3)[http://developer.apple.com/mac/library/DOCUMENTATION/Darwin/Reference/ManPages/man3/dispatch_object.3.html#//apple_ref/doc/man/3/dispatch_object]
* (queue or source). To resume operation, call +resume!+.
*
* gcdq = Dispatch::Queue.new('doc')
* gcdq.dispatch { sleep 1 }
* gcdq.suspend!
* gcdq.suspended? #=> true
* gcdq.resume!
*
*/
static VALUE
rb_dispatch_suspend(VALUE self, SEL sel)
{
rb_dispatch_obj_t *dobj = RDispatch(self);
OSSpinLockLock(&_suspensionLock);
dobj->suspension_count++;
OSSpinLockUnlock(&_suspensionLock);
dispatch_suspend(dobj->obj);
return Qnil;
}
/*
* call-seq:
* obj.resume!
*
* Resumes the operation of a
* dispatch_object(3)[http://developer.apple.com/mac/library/DOCUMENTATION/Darwin/Reference/ManPages/man3/dispatch_object.3.html#//apple_ref/doc/man/3/dispatch_object]
* (queue or source). To suspend operation, call +suspend!+.
*
* gcdq = Dispatch::Queue.new('doc')
* gcdq.dispatch { sleep 1 }
* gcdq.suspend!
* gcdq.suspended? #=> true
* gcdq.resume!
*
*/
static VALUE
rb_dispatch_resume(VALUE self, SEL sel)
{
rb_dispatch_obj_t *dobj = RDispatch(self);
OSSpinLockLock(&_suspensionLock);
if (dobj->suspension_count > 0) {
dobj->suspension_count--;
dispatch_resume(dobj->obj);
}
OSSpinLockUnlock(&_suspensionLock);
return Qnil;
}
/*
* call-seq:
* obj.suspended? => true or false
*
* Returns +true+ if <i>obj</i> is suspended.
*
* gcdq = Dispatch::Queue.new('doc')
* gcdq.dispatch { sleep 1 }
* gcdq.suspend!
* gcdq.suspended? #=> true
* gcdq.resume!
* gcdq.suspended? #=> false
*
*/
static VALUE
rb_dispatch_suspended_p(VALUE self, SEL sel)
{
return (RDispatch(self)->suspension_count == 0) ? Qfalse : Qtrue;
}
static VALUE
rb_group_alloc(VALUE klass, SEL sel)
{
NEWOBJ(group, rb_group_t);
OBJSETUP(group, klass, RUBY_T_NATIVE);
group->suspension_count = 0;
return (VALUE)group;
}
/*
* call-seq:
* Dispatch::Group.new => Dispatch::Group
*
* Returns a Group allowing for aggregate synchronization, as defined in:
* dispatch_group_create(3)[http://developer.apple.com/mac/library/DOCUMENTATION/Darwin/Reference/ManPages/man3/dispatch_group_create.3.html]
* You can dispatch multiple blocks and track when they all complete,
* even though they might run on different queues.
* This behavior can be helpful when progress can not be made until all
* of the specified tasks are complete.
*
* gcdg = Dispatch::Group.new
*
*/
static VALUE
rb_group_init(VALUE self, SEL sel)
{
RGroup(self)->group = dispatch_group_create();
assert(RGroup(self)->group != NULL);
return self;
}
/*
* call-seq:
* grp.notify(queue) { block }
*
* Asynchronously schedules a block to be called when the previously
* submitted dispatches for that group have completed.
*
* gcdq = Dispatch::Queue.new('doc')
* grp = Dispatch::Group.new
* gcdq.async(grp) { print 'foo' }
* grp.notify(gcdq) { print 'bar' } #=> foobar
*/
static VALUE
rb_group_notify(VALUE self, SEL sel, VALUE target)
{
rb_vm_block_t *block = get_prepared_block();
Check_Queue(target);
dispatch_group_notify_f(RGroup(self)->group, RQueue(target)->queue,
(void *)block, rb_block_dispatcher);
return Qnil;
}
/*
* call-seq:
* grp.wait(timeout=nil) => true or false
*
* Waits until all the blocks associated with the +grp+ have
* finished executing or until the specified +timeout+ has elapsed.
* The function will return +true+ if the group became empty within
* the specified amount of time and will return +false+ otherwise.
* If the supplied timeout is nil, the function will wait indefinitely until
* the specified group becomes empty, always returning true.
*
* gcdq = Dispatch::Queue.new('doc')
* grp = Dispatch::Group.new
* gcdq.async(grp) { sleep 4 }
* grp.wait(5) #=> true
*/
static VALUE
rb_group_wait(VALUE self, SEL sel, int argc, VALUE *argv)
{
VALUE num;
rb_scan_args(argc, argv, "01", &num);
return dispatch_group_wait(RGroup(self)->group, rb_num2timeout(num))
== 0 ? Qtrue : Qfalse;
}
static IMP rb_group_finalize_super;
static void
rb_group_finalize(void *rcv, SEL sel)
{
rb_group_t *grp = RGroup(rcv);
if (grp->group != NULL) {
dispatch_release(grp->group);
}
if (rb_group_finalize_super != NULL) {
((void(*)(void *, SEL))rb_group_finalize_super)(rcv, sel);
}
}
static inline dispatch_source_type_t
rb_source_enum2type(source_enum_t value)
{
switch (value)
{
case SOURCE_TYPE_DATA_ADD: return DISPATCH_SOURCE_TYPE_DATA_ADD;
case SOURCE_TYPE_DATA_OR: return DISPATCH_SOURCE_TYPE_DATA_OR;
case SOURCE_TYPE_MACH_SEND: return DISPATCH_SOURCE_TYPE_MACH_SEND;
case SOURCE_TYPE_MACH_RECV: return DISPATCH_SOURCE_TYPE_MACH_RECV;
case SOURCE_TYPE_PROC: return DISPATCH_SOURCE_TYPE_PROC;
case SOURCE_TYPE_READ: return DISPATCH_SOURCE_TYPE_READ;
case SOURCE_TYPE_SIGNAL: return DISPATCH_SOURCE_TYPE_SIGNAL;
case SOURCE_TYPE_TIMER: return DISPATCH_SOURCE_TYPE_TIMER;
case SOURCE_TYPE_VNODE: return DISPATCH_SOURCE_TYPE_VNODE;
case SOURCE_TYPE_WRITE: return DISPATCH_SOURCE_TYPE_WRITE;
default: rb_raise(rb_eArgError,
"Unknown dispatch source type `%d'", value);
}
return NULL;
}
static inline BOOL
rb_source_is_file(rb_source_t *src)
{
source_enum_t value = src->source_enum;
if (value == SOURCE_TYPE_READ || value == SOURCE_TYPE_VNODE
|| value == SOURCE_TYPE_WRITE) {
return true;
}
return false;
}
static VALUE
rb_source_alloc(VALUE klass, SEL sel)
{
NEWOBJ(source, rb_source_t);
OBJSETUP(source, klass, RUBY_T_NATIVE);
source->suspension_count = 1;
return (VALUE)source;
}
static void
rb_source_event_handler(void* sourceptr)
{
assert(sourceptr != NULL);
rb_source_t *source = RSource(sourceptr);
rb_block_arg_dispatcher(source->event_handler, (VALUE) source);
}
static void
rb_source_close_handler(void* sourceptr)
{
assert(sourceptr != NULL);
rb_source_t *src = RSource(sourceptr);
rb_io_close(src->handle);
// Call rb_io_close directly since rb_vm_call aborts inside block
// rb_vm_call(io, selClose, 0, NULL, false);
}
/*
* call-seq:
* Dispatch::Source.new(type, handle, mask, queue) {|src| block}
* => Dispatch::Source
*
* Returns a Source used to monitor a variety of system objects and events,
* using dispatch_source_create(3)[http://developer.apple.com/Mac/library/documentation/Darwin/Reference/ManPages/man3/dispatch_source_create.3.html]
*
* If an IO object (e.g., File) is passed as the handle, it will automatically
* create a cancel handler that closes that file (see +cancel!+ for details).
* The type must be one of:
* - Dispatch::Source::READ (calls +handle.close_read+)
* - Dispatch::Source::WRITE (calls +handle.close_write+)
* - Dispatch::Source::VNODE (calls +handle.close+)
* This is the only way to set the cancel_handler, since in MacRuby
* sources start off resumed. This is safer than closing the file
* yourself, as the cancel handler is guaranteed to only run once,
* and only after all pending events are processed.
* If you do *not* want the file closed on cancel, simply use
* +file.to_i+ to instead pass a descriptor as the handle.
*/
static VALUE
rb_source_init(VALUE self, SEL sel,
VALUE type, VALUE handle, VALUE mask, VALUE queue)
{
Check_Queue(queue);
rb_source_t *src = RSource(self);
src->source_enum = (source_enum_t) NUM2LONG(type);
dispatch_source_type_t c_type = rb_source_enum2type(src->source_enum);
assert(c_type != NULL);
uintptr_t c_handle = NUM2UINT(rb_Integer(handle));
unsigned long c_mask = NUM2LONG(mask);
dispatch_queue_t c_queue = RQueue(queue)->queue;
src->source = dispatch_source_create(c_type, c_handle, c_mask, c_queue);
assert(src->source != NULL);
rb_vm_block_t *block = get_prepared_block();
GC_WB(&src->event_handler, block);
GC_RETAIN(self); // apparently needed to ensure consistent counting
dispatch_set_context(src->source, (void *)self);
dispatch_source_set_event_handler_f(src->source, rb_source_event_handler);
GC_WB(&src->handle, handle);
if (rb_source_is_file(src) && rb_obj_is_kind_of(handle, rb_cIO)) {
dispatch_source_set_cancel_handler_f(src->source,
rb_source_close_handler);
}
rb_dispatch_resume(self, 0);
return self;
}
/*
* call-seq:
* Dispatch::Source.timer(delay, interval, leeway, queue)
* => Dispatch::Source
*
* Returns a Source that will submit the event handler block to
* the target queue after delay, repeated at interval, within leeway, via
* a call to dispatch_source_set_timer(3)[http://developer.apple.com/mac/library/DOCUMENTATION/Darwin/Reference/ManPages/man3/dispatch_source_set_timer.3.html].
* A best effort attempt is made to submit the event handler block to the
* target queue at the specified time; however, actual invocation may occur at
* a later time even if the leeway is zero.
*
* gcdq = Dispatch::Queue.new('doc')
* timer = Dispatch::Source.timer(0, 5, 0.1, gcdq) do |s|
* puts s.data
* end
*
*/
static VALUE
rb_source_timer(VALUE klass, VALUE sel, VALUE delay, VALUE interval, VALUE leeway, VALUE queue)
{
Check_Queue(queue);
dispatch_time_t start_time;
VALUE argv[4] = {INT2FIX(SOURCE_TYPE_TIMER),
INT2FIX(0), INT2FIX(0), queue};
VALUE self = rb_class_new_instance(4, argv, cSource);
rb_source_t *src = RSource(self);
if (NIL_P(leeway)) {
leeway = INT2FIX(0);
}
if (NIL_P(delay)) {
start_time = DISPATCH_TIME_NOW;
}
else {
start_time = rb_num2timeout(delay);
}
rb_dispatch_suspend(self, 0);
dispatch_source_set_timer(src->source, start_time,
rb_num2nsec(interval), rb_num2nsec(leeway));
rb_dispatch_resume(self, 0);
return self;
}
/*