1. # Thread represents an OS-level thread. While it could be used directly, it
  2. # is not the preferred way to work in Perl 6. It's a building block for the
  3. # interesting things.
  4. my class Thread {
  5. # The VM-level thread handle.
  6. has Mu $!vm_thread;
  7. # Is the thread's lifetime bounded by that of the application, such
  8. # that when it exits, so does the thread?
  9. has Bool $.app_lifetime;
  10. # Thread's (user-defined) name.
  11. has Str $.name;
  12. submethod BUILD(
  13. :&code!,
  14. Bool() :$!app_lifetime = False,
  15. Str() :$!name = "<anon>"
  16. --> Nil
  17. ) {
  18. $!vm_thread := nqp::newthread(
  19. anon sub THREAD-ENTRY() {
  20. my $*THREAD = self;
  21. CONTROL {
  22. default {
  23. my Mu $vm-ex := nqp::getattr(nqp::decont($_), Exception, '$!ex');
  24. nqp::getcomp('perl6').handle-control($vm-ex);
  25. }
  26. }
  27. code();
  28. },
  29. $!app_lifetime ?? 1 !! 0);
  30. }
  31. method start(Thread:U: &code, *%adverbs) {
  32. Thread.new(:&code, |%adverbs).run()
  33. }
  34. method run(Thread:D:) {
  35. nqp::threadrun($!vm_thread);
  36. self
  37. }
  38. method id(Thread:D:) {
  39. nqp::p6box_i(nqp::threadid($!vm_thread));
  40. }
  41. method finish(Thread:D:) {
  42. nqp::threadjoin($!vm_thread);
  43. self
  44. }
  45. method join(Thread:D:) {
  46. self.finish
  47. }
  48. multi method Numeric(Thread:D:) {
  49. self.id
  50. }
  51. multi method Str(Thread:D:) {
  52. "Thread<$.id>($.name)"
  53. }
  54. multi method gist(Thread:D:) {
  55. "Thread #$.id" ~ ($!name ne '<anon>' ?? " ($!name)" !! '')
  56. }
  57. method yield(Thread:U: --> Nil) {
  58. nqp::threadyield();
  59. }
  60. }
  61. Rakudo::Internals.REGISTER-DYNAMIC: '$*THREAD', {
  62. my $init_thread := nqp::create(Thread);
  63. nqp::bindattr($init_thread, Thread, '$!vm_thread', nqp::currentthread());
  64. nqp::bindattr($init_thread, Thread, '$!app_lifetime', False);
  65. nqp::bindattr($init_thread, Thread, '$!name', 'Initial thread');
  66. PROCESS::<$THREAD> := $init_thread;
  67. }