forked from MacRuby/MacRuby
-
Notifications
You must be signed in to change notification settings - Fork 0
/
thread.c
1659 lines (1463 loc) · 39.6 KB
/
thread.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 implementation of Thread.
*
* This file is covered by the Ruby license. See COPYING for more details.
*
* Copyright (C) 2009-2010, Apple Inc. All rights reserved.
* Copyright (C) 2004-2007 Koichi Sasada
*/
#include "ruby/macruby.h"
#include "ruby/node.h"
#include "vm.h"
#include "objc.h"
VALUE rb_cThread;
VALUE rb_cThGroup;
VALUE rb_cMutex;
typedef struct rb_vm_mutex {
pthread_mutex_t mutex;
rb_vm_thread_t *thread;
} rb_vm_mutex_t;
#define GetMutexPtr(obj) ((rb_vm_mutex_t *)DATA_PTR(obj))
typedef struct {
bool enclosed;
VALUE threads;
VALUE mutex;
} rb_thread_group_t;
#define GetThreadGroupPtr(obj) ((rb_thread_group_t *)DATA_PTR(obj))
#if 0
static VALUE
thread_s_new(int argc, VALUE *argv, VALUE klass)
{
// TODO
return Qnil;
}
#endif
static VALUE
thread_s_alloc(VALUE rcv, SEL sel)
{
rb_vm_thread_t *t = (rb_vm_thread_t *)xmalloc(sizeof(rb_vm_thread_t));
t->thread = 0;
return Data_Wrap_Struct(rb_cThread, NULL, NULL, t);
}
static IMP
thread_finalize_imp_super = NULL;
static void
thread_finalize_imp(void *rcv, SEL sel)
{
rb_vm_thread_t *t = GetThreadPtr(rcv);
if (t->exception != Qnil && !t->joined_on_exception) {
fprintf(stderr, "*** Thread %p exited prematurely because of an uncaught exception:\n%s\n",
t->thread,
rb_str_cstr(rb_format_exception_message(t->exception)));
}
if (thread_finalize_imp_super != NULL) {
((void(*)(void *, SEL))thread_finalize_imp_super)(rcv, sel);
}
}
static VALUE
thread_initialize(VALUE thread, SEL sel, int argc, const VALUE *argv)
{
if (!rb_block_given_p()) {
rb_raise(rb_eThreadError, "must be called with a block");
}
rb_vm_block_t *b = rb_vm_current_block();
assert(b != NULL);
rb_vm_thread_t *t = GetThreadPtr(thread);
if (t->thread != 0) {
rb_raise(rb_eThreadError, "already initialized thread");
}
rb_vm_thread_pre_init(t, b, argc, argv, rb_vm_create_vm());
// The thread's group is always the parent's one.
// The parent group might be nil (ex. if created from GCD).
VALUE group = GetThreadPtr(rb_vm_current_thread())->group;
if (group != Qnil) {
rb_thgroup_add(group, thread);
}
// Retain the Thread object to avoid a potential GC, the corresponding
// release is done in rb_vm_thread_run().
GC_RETAIN(thread);
// Prepare attributes for the thread.
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED);
pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
// Launch it.
if (pthread_create(&t->thread, &attr, (void *(*)(void *))rb_vm_thread_run,
(void *)thread) != 0) {
rb_sys_fail("pthread_create() failed");
}
pthread_attr_destroy(&attr);
return thread;
}
/*
* call-seq:
* Thread.start([args]*) {|args| block } => thread
* Thread.fork([args]*) {|args| block } => thread
*
* Basically the same as <code>Thread::new</code>. However, if class
* <code>Thread</code> is subclassed, then calling <code>start</code> in that
* subclass will not invoke the subclass's <code>initialize</code> method.
*/
static VALUE
thread_start(VALUE klass, SEL sel, int argc, VALUE *argv)
{
VALUE th = thread_s_alloc(klass, 0);
return thread_initialize(th, 0, argc, argv);
}
VALUE
rb_thread_create(VALUE (*fn)(ANYARGS), void *arg)
{
// TODO
return Qnil;
}
/*
* call-seq:
* thr.join => thr
* thr.join(limit) => thr
*
* The calling thread will suspend execution and run <i>thr</i>. Does not
* return until <i>thr</i> exits or until <i>limit</i> seconds have passed. If
* the time limit expires, <code>nil</code> will be returned, otherwise
* <i>thr</i> is returned.
*
* Any threads not joined will be killed when the main program exits. If
* <i>thr</i> had previously raised an exception and the
* <code>abort_on_exception</code> and <code>$DEBUG</code> flags are not set
* (so the exception has not yet been processed) it will be processed at this
* time.
*
* a = Thread.new { print "a"; sleep(10); print "b"; print "c" }
* x = Thread.new { print "x"; Thread.pass; print "y"; print "z" }
* x.join # Let x thread finish, a will be killed on exit.
*
* <em>produces:</em>
*
* axyz
*
* The following example illustrates the <i>limit</i> parameter.
*
* y = Thread.new { 4.times { sleep 0.1; puts 'tick... ' }}
* puts "Waiting" until y.join(0.15)
*
* <em>produces:</em>
*
* tick...
* Waiting
* tick...
* Waitingtick...
*
*
* tick...
*/
static VALUE
thread_join_m(VALUE self, SEL sel, int argc, VALUE *argv)
{
VALUE timeout;
rb_scan_args(argc, argv, "01", &timeout);
rb_vm_thread_t *t = GetThreadPtr(self);
if (t->status != THREAD_DEAD) {
if (timeout == Qnil) {
// No timeout given: block until the thread finishes.
//pthread_assert(pthread_join(t->thread, NULL));
struct timespec ts;
ts.tv_sec = 0;
ts.tv_nsec = 10000000;
while (t->status != THREAD_DEAD) {
nanosleep(&ts, NULL);
pthread_yield_np();
}
}
else {
// Timeout given: sleep and check if the thread is dead.
struct timeval tv = rb_time_interval(timeout);
struct timespec ts;
ts.tv_sec = tv.tv_sec;
ts.tv_nsec = tv.tv_usec * 1000;
while (ts.tv_nsec >= 1000000000) {
ts.tv_sec += 1;
ts.tv_nsec -= 1000000000;
}
while (ts.tv_sec > 0 || ts.tv_nsec > 0) {
struct timespec its;
again:
if (ts.tv_nsec > 100000000) {
ts.tv_nsec -= 100000000;
its.tv_sec = 0;
its.tv_nsec = 100000000;
}
else if (ts.tv_sec > 0) {
ts.tv_sec -= 1;
ts.tv_nsec += 1000000000;
goto again;
}
else {
its = ts;
ts.tv_sec = ts.tv_nsec = 0;
}
nanosleep(&its, NULL);
if (t->status == THREAD_DEAD) {
goto dead;
}
}
return Qnil;
}
}
dead:
// If the thread was terminated because of an exception, we need to
// propagate it.
if (t->exception != Qnil) {
t->joined_on_exception = true;
rb_exc_raise(t->exception);
}
return self;
}
/*
* call-seq:
* thr.value => obj
*
* Waits for <i>thr</i> to complete (via <code>Thread#join</code>) and returns
* its value.
*
* a = Thread.new { 2 + 2 }
* a.value #=> 4
*/
static VALUE
thread_value(VALUE self, SEL sel)
{
thread_join_m(self, 0, 0, NULL);
return GetThreadPtr(self)->value;
}
void
rb_thread_polling(void)
{
// TODO
}
void
rb_thread_schedule(void)
{
// TODO
}
int rb_thread_critical; /* TODO: dummy variable */
/*
* call-seq:
* Thread.pass => nil
*
* Invokes the thread scheduler to pass execution to another thread.
*
* a = Thread.new { print "a"; Thread.pass;
* print "b"; Thread.pass;
* print "c" }
* b = Thread.new { print "x"; Thread.pass;
* print "y"; Thread.pass;
* print "z" }
* a.join
* b.join
*
* <em>produces:</em>
*
* axbycz
*/
static VALUE
thread_s_pass(VALUE klass, SEL sel)
{
pthread_yield_np();
return Qnil;
}
/*
* call-seq:
* thr.raise(exception)
*
* Raises an exception (see <code>Kernel::raise</code>) from <i>thr</i>. The
* caller does not have to be <i>thr</i>.
*
* Thread.abort_on_exception = true
* a = Thread.new { sleep(200) }
* a.raise("Gotcha")
*
* <em>produces:</em>
*
* prog.rb:3: Gotcha (RuntimeError)
* from prog.rb:2:in `initialize'
* from prog.rb:2:in `new'
* from prog.rb:2
*/
static VALUE
thread_raise_m(VALUE self, SEL sel, int argc, VALUE *argv)
{
VALUE exc = rb_make_exception(argc, argv);
rb_vm_thread_t *t = GetThreadPtr(self);
if (t->thread == pthread_self()) {
rb_exc_raise(exc);
}
else if (t->status != THREAD_DEAD) {
rb_vm_thread_raise(t, exc);
}
return Qnil;
}
/*
* call-seq:
* thr.exit => thr
* thr.kill => thr
* thr.terminate => thr
*
* Terminates <i>thr</i> and schedules another thread to be run. If this thread
* is already marked to be killed, <code>exit</code> returns the
* <code>Thread</code>. If this is the main thread, or the last thread, exits
* the process.
*/
static VALUE
rb_thread_kill(VALUE thread, SEL sel)
{
rb_vm_thread_t *t = GetThreadPtr(thread);
rb_vm_thread_t *t_main = GetThreadPtr(rb_vm_main_thread());
if (t->thread == t_main->thread) {
rb_exit(EXIT_SUCCESS);
}
if (t->status != THREAD_KILLED) {
rb_vm_thread_cancel(t);
}
return thread;
}
/*
* call-seq:
* Thread.kill(thread) => thread
*
* Causes the given <em>thread</em> to exit (see <code>Thread::exit</code>).
*
* count = 0
* a = Thread.new { loop { count += 1 } }
* sleep(0.1) #=> 0
* Thread.kill(a) #=> #<Thread:0x401b3d30 dead>
* count #=> 93947
* a.alive? #=> false
*/
static VALUE
rb_thread_s_kill(VALUE obj, SEL sel, VALUE th)
{
return rb_thread_kill(th, 0);
}
/*
* call-seq:
* Thread.exit => thread
*
* Terminates the currently running thread and schedules another thread to be
* run. If this thread is already marked to be killed, <code>exit</code>
* returns the <code>Thread</code>. If this is the main thread, or the last
* thread, exit the process.
*/
static VALUE
rb_thread_exit(void)
{
return rb_thread_kill(rb_vm_current_thread(), 0);
}
/*
* call-seq:
* thr.wakeup => thr
*
* Marks <i>thr</i> as eligible for scheduling (it may still remain blocked on
* I/O, however). Does not invoke the scheduler (see <code>Thread#run</code>).
*
* c = Thread.new { Thread.stop; puts "hey!" }
* c.wakeup
*
* <em>produces:</em>
*
* hey!
*/
static VALUE
rb_thread_wakeup(VALUE thread, SEL sel)
{
rb_vm_thread_wakeup(GetThreadPtr(thread));
return thread;
}
/*
* call-seq:
* thr.run => thr
*
* Wakes up <i>thr</i>, making it eligible for scheduling.
*
* a = Thread.new { puts "a"; Thread.stop; puts "c" }
* Thread.pass
* puts "Got here"
* a.run
* a.join
*
* <em>produces:</em>
*
* a
* Got here
* c
*/
static VALUE
rb_thread_run(VALUE thread, SEL sel)
{
rb_vm_thread_wakeup(GetThreadPtr(thread));
pthread_yield_np();
return thread;
}
/*
* call-seq:
* Thread.stop => nil
*
* Stops execution of the current thread, putting it into a ``sleep'' state,
* and schedules execution of another thread.
*
* a = Thread.new { print "a"; Thread.stop; print "c" }
* Thread.pass
* print "b"
* a.run
* a.join
*
* <em>produces:</em>
*
* abc
*/
static VALUE
rb_thread_stop(VALUE rcv, SEL sel)
{
rb_thread_sleep_forever();
return Qnil;
}
/*
* call-seq:
* Thread.list => array
*
* Returns an array of <code>Thread</code> objects for all threads that are
* either runnable or stopped.
*
* Thread.new { sleep(200) }
* Thread.new { 1000000.times {|i| i*i } }
* Thread.new { Thread.stop }
* Thread.list.each {|t| p t}
*
* <em>produces:</em>
*
* #<Thread:0x401b3e84 sleep>
* #<Thread:0x401b3f38 run>
* #<Thread:0x401b3fb0 sleep>
* #<Thread:0x401bdf4c run>
*/
VALUE
rb_thread_list(VALUE rcv, SEL sel)
{
return rb_ary_dup(rb_vm_threads());
}
/*
* call-seq:
* Thread.current => thread
*
* Returns the currently executing thread.
*
* Thread.current #=> #<Thread:0x401bdf4c run>
*/
static VALUE
thread_s_current(VALUE klass, SEL sel)
{
return rb_vm_current_thread();
}
static VALUE
rb_thread_s_main(VALUE klass, SEL sel)
{
return rb_vm_main_thread();
}
/*
* call-seq:
* Thread.abort_on_exception => true or false
*
* Returns the status of the global ``abort on exception'' condition. The
* default is <code>false</code>. When set to <code>true</code>, or if the
* global <code>$DEBUG</code> flag is <code>true</code> (perhaps because the
* command line option <code>-d</code> was specified) all threads will abort
* (the process will <code>exit(0)</code>) if an exception is raised in any
* thread. See also <code>Thread::abort_on_exception=</code>.
*/
static VALUE
rb_thread_s_abort_exc(VALUE rcv, SEL sel)
{
return rb_vm_abort_on_exception() ? Qtrue : Qfalse;
}
/*
* call-seq:
* Thread.abort_on_exception= boolean => true or false
*
* When set to <code>true</code>, all threads will abort if an exception is
* raised. Returns the new state.
*
* Thread.abort_on_exception = true
* t1 = Thread.new do
* puts "In new thread"
* raise "Exception from thread"
* end
* sleep(1)
* puts "not reached"
*
* <em>produces:</em>
*
* In new thread
* prog.rb:4: Exception from thread (RuntimeError)
* from prog.rb:2:in `initialize'
* from prog.rb:2:in `new'
* from prog.rb:2
*/
static VALUE
rb_thread_s_abort_exc_set(VALUE self, SEL sel, VALUE val)
{
rb_vm_set_abort_on_exception(RTEST(val));
return val;
}
/*
* call-seq:
* thr.abort_on_exception => true or false
*
* Returns the status of the thread-local ``abort on exception'' condition for
* <i>thr</i>. The default is <code>false</code>. See also
* <code>Thread::abort_on_exception=</code>.
*/
static VALUE
rb_thread_abort_exc(VALUE thread, SEL sel)
{
return GetThreadPtr(thread)->abort_on_exception ? Qtrue : Qfalse;
}
/*
* call-seq:
* thr.abort_on_exception= boolean => true or false
*
* When set to <code>true</code>, causes all threads (including the main
* program) to abort if an exception is raised in <i>thr</i>. The process will
* effectively <code>exit(0)</code>.
*/
static VALUE
rb_thread_abort_exc_set(VALUE thread, SEL sel, VALUE val)
{
GetThreadPtr(thread)->abort_on_exception = RTEST(val);
return val;
}
/*
* call-seq:
* thr.group => thgrp or nil
*
* Returns the <code>ThreadGroup</code> which contains <i>thr</i>, or nil if
* the thread is not a member of any group.
*
* Thread.main.group #=> #<ThreadGroup:0x4029d914>
*/
static VALUE
rb_thread_group(VALUE thread, SEL sel)
{
return GetThreadPtr(thread)->group;
}
/*
* call-seq:
* thr.status => string, false or nil
*
* Returns the status of <i>thr</i>: ``<code>sleep</code>'' if <i>thr</i> is
* sleeping or waiting on I/O, ``<code>run</code>'' if <i>thr</i> is executing,
* ``<code>aborting</code>'' if <i>thr</i> is aborting, <code>false</code> if
* <i>thr</i> terminated normally, and <code>nil</code> if <i>thr</i>
* terminated with an exception.
*
* a = Thread.new { raise("die now") }
* b = Thread.new { Thread.stop }
* c = Thread.new { Thread.exit }
* d = Thread.new { sleep }
* d.kill #=> #<Thread:0x401b3678 aborting>
* a.status #=> nil
* b.status #=> "sleep"
* c.status #=> false
* d.status #=> "aborting"
* Thread.current.status #=> "run"
*/
static const char *
rb_thread_status_cstr(VALUE thread)
{
rb_vm_thread_t *t = GetThreadPtr(thread);
switch (t->status) {
case THREAD_ALIVE:
return "run";
case THREAD_SLEEP:
return "sleep";
case THREAD_KILLED:
return "aborting";
case THREAD_DEAD:
return "dead";
}
return "unknown";
}
static VALUE
rb_thread_status(VALUE thread, SEL sel)
{
rb_vm_thread_t *t = GetThreadPtr(thread);
if (t->status == THREAD_DEAD) {
return t->exception == Qnil ? Qfalse : Qnil;
}
return rb_str_new2(rb_thread_status_cstr(thread));
}
/*
* call-seq:
* thr.alive? => true or false
*
* Returns <code>true</code> if <i>thr</i> is running or sleeping.
*
* thr = Thread.new { }
* thr.join #=> #<Thread:0x401b3fb0 dead>
* Thread.current.alive? #=> true
* thr.alive? #=> false
*/
static VALUE
rb_thread_alive_p(VALUE thread, SEL sel)
{
rb_vm_thread_status_t s = GetThreadPtr(thread)->status;
return s != THREAD_DEAD ? Qtrue : Qfalse;
}
/*
* call-seq:
* thr.stop? => true or false
*
* Returns <code>true</code> if <i>thr</i> is dead or sleeping.
*
* a = Thread.new { Thread.stop }
* b = Thread.current
* a.stop? #=> true
* b.stop? #=> false
*/
static VALUE
rb_thread_stop_p(VALUE thread)
{
rb_vm_thread_status_t s = GetThreadPtr(thread)->status;
return s == THREAD_DEAD || s == THREAD_SLEEP ? Qtrue : Qfalse;
}
/*
* call-seq:
* thr.safe_level => integer
*
* Returns the safe level in effect for <i>thr</i>. Setting thread-local safe
* levels can help when implementing sandboxes which run insecure code.
*
* thr = Thread.new { $SAFE = 3; sleep }
* Thread.current.safe_level #=> 0
* thr.safe_level #=> 3
*/
static VALUE
rb_thread_safe_level(VALUE thread, SEL sel)
{
return INT2FIX(rb_vm_thread_safe_level(GetThreadPtr(thread)));
}
/*
* call-seq:
* thr.inspect => string
*
* Dump the name, id, and status of _thr_ to a string.
*/
static VALUE
rb_thread_inspect(VALUE thread, SEL sel)
{
const char *status = rb_thread_status_cstr(thread);
char buf[100];
snprintf(buf, sizeof buf, "#<%s:%p %s>", rb_obj_classname(thread),
(void *)thread, status);
return rb_str_new2(buf);
}
/*
* call-seq:
* thr[sym] => obj or nil
*
* Attribute Reference---Returns the value of a thread-local variable, using
* either a symbol or a string name. If the specified variable does not exist,
* returns <code>nil</code>.
*
* a = Thread.new { Thread.current["name"] = "A"; Thread.stop }
* b = Thread.new { Thread.current[:name] = "B"; Thread.stop }
* c = Thread.new { Thread.current["name"] = "C"; Thread.stop }
* Thread.list.each {|x| puts "#{x.inspect}: #{x[:name]}" }
*
* <em>produces:</em>
*
* #<Thread:0x401b3b3c sleep>: C
* #<Thread:0x401b3bc8 sleep>: B
* #<Thread:0x401b3c68 sleep>: A
* #<Thread:0x401bdf4c run>:
*/
static VALUE
rb_thread_aref(VALUE thread, SEL sel, VALUE key)
{
key = ID2SYM(rb_to_id(key));
VALUE h = rb_vm_thread_locals(thread, false);
if (h != Qnil) {
return rb_hash_aref(h, key);
}
return Qnil;
}
VALUE
rb_thread_local_aref(VALUE self, ID key)
{
return rb_thread_aref(self, 0, ID2SYM(key));
}
/*
* call-seq:
* thr[sym] = obj => obj
*
* Attribute Assignment---Sets or creates the value of a thread-local variable,
* using either a symbol or a string. See also <code>Thread#[]</code>.
*/
static VALUE
rb_thread_aset(VALUE self, SEL sel, VALUE key, VALUE val)
{
key = ID2SYM(rb_to_id(key));
return rb_hash_aset(rb_vm_thread_locals(self, true), key, val);
}
VALUE
rb_thread_local_aset(VALUE self, ID key, VALUE val)
{
return rb_thread_aset(self, 0, ID2SYM(key), val);
}
/*
* call-seq:
* thr.key?(sym) => true or false
*
* Returns <code>true</code> if the given string (or symbol) exists as a
* thread-local variable.
*
* me = Thread.current
* me[:oliver] = "a"
* me.key?(:oliver) #=> true
* me.key?(:stanley) #=> false
*/
static VALUE
rb_thread_key_p(VALUE self, SEL sel, VALUE key)
{
key = ID2SYM(rb_to_id(key));
VALUE h = rb_vm_thread_locals(self, false);
if (h == Qnil) {
return Qfalse;
}
return rb_hash_has_key(h, key);
}
int
rb_thread_alone()
{
return RARRAY_LEN(rb_vm_threads()) <= 1;
}
/*
* call-seq:
* thr.keys => array
*
* Returns an an array of the names of the thread-local variables (as Symbols).
*
* thr = Thread.new do
* Thread.current[:cat] = 'meow'
* Thread.current["dog"] = 'woof'
* end
* thr.join #=> #<Thread:0x401b3f10 dead>
* thr.keys #=> [:dog, :cat]
*/
static VALUE
rb_thread_keys(VALUE self, SEL sel)
{
VALUE h = rb_vm_thread_locals(self, false);
return h == Qnil ? rb_ary_new() : rb_hash_keys(h);
}
/*
* call-seq:
* thr.priority => integer
*
* Returns the priority of <i>thr</i>. Default is inherited from the
* current thread which creating the new thread, or zero for the
* initial main thread; higher-priority threads will run before
* lower-priority threads.
*
* Thread.current.priority #=> 0
*/
static VALUE
rb_thread_priority(VALUE thread, SEL sel)
{
// FIXME this doesn't really minic what 1.9 does, but do we care?
struct sched_param param;
pthread_assert(pthread_getschedparam(GetThreadPtr(thread)->thread,
NULL, ¶m));
return INT2FIX(param.sched_priority);
}
/*
* call-seq:
* thr.priority= integer => thr
*
* Sets the priority of <i>thr</i> to <i>integer</i>. Higher-priority threads
* will run before lower-priority threads.
*
* count1 = count2 = 0
* a = Thread.new do
* loop { count1 += 1 }
* end
* a.priority = -1
*
* b = Thread.new do
* loop { count2 += 1 }
* end
* b.priority = -2
* sleep 1 #=> 1
* count1 #=> 622504
* count2 #=> 5832
*/
static VALUE
rb_thread_priority_set(VALUE thread, SEL sel, VALUE prio)
{
// FIXME this doesn't really minic what 1.9 does, but do we care?
int policy;
struct sched_param param;
pthread_assert(pthread_getschedparam(GetThreadPtr(thread)->thread,
&policy, ¶m));
const int max = sched_get_priority_max(policy);
const int min = sched_get_priority_min(policy);
int priority = FIX2INT(prio);
if (min > priority) {
priority = min;
}
else if (max > priority) {
priority = max;
}
param.sched_priority = priority;
pthread_assert(pthread_setschedparam(GetThreadPtr(thread)->thread,
policy, ¶m));
return Qnil;
}
/* for IO */
// TODO these should be moved into io.c
#if defined(NFDBITS) && defined(HAVE_RB_FD_INIT)
void
rb_fd_init(volatile rb_fdset_t *fds)
{
fds->maxfd = 0;
GC_WB(&fds->fdset, ALLOC(fd_set));
FD_ZERO(fds->fdset);
}
void
rb_fd_term(rb_fdset_t *fds)
{
if (fds->fdset) xfree(fds->fdset);
fds->maxfd = 0;
fds->fdset = 0;
}
void
rb_fd_zero(rb_fdset_t *fds)
{
if (fds->fdset) {
MEMZERO(fds->fdset, fd_mask, howmany(fds->maxfd, NFDBITS));
FD_ZERO(fds->fdset);
}
}
static void
rb_fd_resize(int n, rb_fdset_t *fds)
{
int m = howmany(n + 1, NFDBITS) * sizeof(fd_mask);
int o = howmany(fds->maxfd, NFDBITS) * sizeof(fd_mask);
if (m < sizeof(fd_set)) m = sizeof(fd_set);
if (o < sizeof(fd_set)) o = sizeof(fd_set);
if (m > o) {
GC_WB(&fds->fdset, xrealloc(fds->fdset, m));
memset((char *)fds->fdset + o, 0, m - o);
}
if (n >= fds->maxfd) fds->maxfd = n + 1;
}
void
rb_fd_set(int n, rb_fdset_t *fds)
{
rb_fd_resize(n, fds);
FD_SET(n, fds->fdset);
}
void
rb_fd_clr(int n, rb_fdset_t *fds)
{
if (n >= fds->maxfd) return;
FD_CLR(n, fds->fdset);
}
int
rb_fd_isset(int n, const rb_fdset_t *fds)
{
if (n >= fds->maxfd) return 0;
return FD_ISSET(n, fds->fdset) != 0; /* "!= 0" avoids FreeBSD PR 91421 */
}
void
rb_fd_copy(rb_fdset_t *dst, const fd_set *src, int max)
{
int size = howmany(max, NFDBITS) * sizeof(fd_mask);
if (size < sizeof(fd_set)) size = sizeof(fd_set);
dst->maxfd = max;
GC_WB(&dst->fdset, xrealloc(dst->fdset, size));
memcpy(dst->fdset, src, size);
}