This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Convert the Pod::Perldoc tests from Test to Test::More.
[perl5.git] / dist / threads / threads.xs
1 #define PERL_NO_GET_CONTEXT
2 #include "EXTERN.h"
3 #include "perl.h"
4 #include "XSUB.h"
5 /* Workaround for XSUB.h bug under WIN32 */
6 #ifdef WIN32
7 #  undef setjmp
8 #  if !defined(__BORLANDC__)
9 #    define setjmp(x) _setjmp(x)
10 #  endif
11 #endif
12 #ifdef HAS_PPPORT_H
13 #  define NEED_PL_signals
14 #  define NEED_newRV_noinc
15 #  define NEED_sv_2pv_flags
16 #  include "ppport.h"
17 #  include "threads.h"
18 #endif
19
20 #ifdef USE_ITHREADS
21
22 #ifdef WIN32
23 #  include <windows.h>
24    /* Supposed to be in Winbase.h */
25 #  ifndef STACK_SIZE_PARAM_IS_A_RESERVATION
26 #    define STACK_SIZE_PARAM_IS_A_RESERVATION 0x00010000
27 #  endif
28 #  include <win32thread.h>
29 #else
30 #  ifdef OS2
31 typedef perl_os_thread pthread_t;
32 #  else
33 #    include <pthread.h>
34 #  endif
35 #  include <thread.h>
36 #  define PERL_THREAD_SETSPECIFIC(k,v) pthread_setspecific(k,v)
37 #  ifdef OLD_PTHREADS_API
38 #    define PERL_THREAD_DETACH(t) pthread_detach(&(t))
39 #  else
40 #    define PERL_THREAD_DETACH(t) pthread_detach((t))
41 #  endif
42 #endif
43 #if !defined(HAS_GETPAGESIZE) && defined(I_SYS_PARAM)
44 #  include <sys/param.h>
45 #endif
46
47 /* Values for 'state' member */
48 #define PERL_ITHR_DETACHED           1 /* Thread has been detached */
49 #define PERL_ITHR_JOINED             2 /* Thread has been joined */
50 #define PERL_ITHR_FINISHED           4 /* Thread has finished execution */
51 #define PERL_ITHR_THREAD_EXIT_ONLY   8 /* exit() only exits current thread */
52 #define PERL_ITHR_NONVIABLE         16 /* Thread creation failed */
53 #define PERL_ITHR_DIED              32 /* Thread finished by dying */
54
55 #define PERL_ITHR_UNCALLABLE  (PERL_ITHR_DETACHED|PERL_ITHR_JOINED)
56
57
58 typedef struct _ithread {
59     struct _ithread *next;      /* Next thread in the list */
60     struct _ithread *prev;      /* Prev thread in the list */
61     PerlInterpreter *interp;    /* The threads interpreter */
62     UV tid;                     /* Threads module's thread id */
63     perl_mutex mutex;           /* Mutex for updating things in this struct */
64     int count;                  /* Reference count. See S_ithread_create. */
65     int state;                  /* Detached, joined, finished, etc. */
66     int gimme;                  /* Context of create */
67     SV *init_function;          /* Code to run */
68     SV *params;                 /* Args to pass function */
69 #ifdef WIN32
70     DWORD  thr;                 /* OS's idea if thread id */
71     HANDLE handle;              /* OS's waitable handle */
72 #else
73     pthread_t thr;              /* OS's handle for the thread */
74 #endif
75     IV stack_size;
76     SV *err;                    /* Error from abnormally terminated thread */
77     char *err_class;            /* Error object's classname if applicable */
78 #ifndef WIN32
79     sigset_t initial_sigmask;   /* Thread wakes up with signals blocked */
80 #endif
81 } ithread;
82
83
84 #define MY_CXT_KEY "threads::_cxt" XS_VERSION
85
86 typedef struct {
87     /* Used by Perl interpreter for thread context switching */
88     ithread *context;
89 } my_cxt_t;
90
91 START_MY_CXT
92
93
94 #define MY_POOL_KEY "threads::_pool" XS_VERSION
95
96 typedef struct {
97     /* Structure for 'main' thread
98      * Also forms the 'base' for the doubly-linked list of threads */
99     ithread main_thread;
100
101     /* Protects the creation and destruction of threads*/
102     perl_mutex create_destruct_mutex;
103
104     UV tid_counter;
105     IV joinable_threads;
106     IV running_threads;
107     IV detached_threads;
108     IV total_threads;
109     IV default_stack_size;
110     IV page_size;
111 } my_pool_t;
112
113 #define dMY_POOL \
114     SV *my_pool_sv = *hv_fetch(PL_modglobal, MY_POOL_KEY,               \
115                                sizeof(MY_POOL_KEY)-1, TRUE);            \
116     my_pool_t *my_poolp = INT2PTR(my_pool_t*, SvUV(my_pool_sv))
117
118 #define MY_POOL (*my_poolp)
119
120 #ifndef WIN32
121 /* Block most signals for calling thread, setting the old signal mask to
122  * oldmask, if it is not NULL */
123 STATIC int
124 S_block_most_signals(sigset_t *oldmask)
125 {
126     sigset_t newmask;
127
128     sigfillset(&newmask);
129     /* Don't block certain "important" signals (stolen from mg.c) */
130 #ifdef SIGILL
131     sigdelset(&newmask, SIGILL);
132 #endif
133 #ifdef SIGBUS
134     sigdelset(&newmask, SIGBUS);
135 #endif
136 #ifdef SIGSEGV
137     sigdelset(&newmask, SIGSEGV);
138 #endif
139
140 #if defined(VMS)
141     /* no per-thread blocking available */
142     return sigprocmask(SIG_BLOCK, &newmask, oldmask);
143 #else
144     return pthread_sigmask(SIG_BLOCK, &newmask, oldmask);
145 #endif /* VMS */
146 }
147
148 /* Set the signal mask for this thread to newmask */
149 STATIC int
150 S_set_sigmask(sigset_t *newmask)
151 {
152 #if defined(VMS)
153     return sigprocmask(SIG_SETMASK, newmask, NULL);
154 #else
155     return pthread_sigmask(SIG_SETMASK, newmask, NULL);
156 #endif /* VMS */
157 }
158 #endif /* WIN32 */
159
160 /* Used by Perl interpreter for thread context switching */
161 STATIC void
162 S_ithread_set(pTHX_ ithread *thread)
163 {
164     dMY_CXT;
165     MY_CXT.context = thread;
166 }
167
168 STATIC ithread *
169 S_ithread_get(pTHX)
170 {
171     dMY_CXT;
172     return (MY_CXT.context);
173 }
174
175
176 /* Free any data (such as the Perl interpreter) attached to an ithread
177  * structure.  This is a bit like undef on SVs, where the SV isn't freed,
178  * but the PVX is.  Must be called with thread->mutex already locked.  Also,
179  * must be called with MY_POOL.create_destruct_mutex unlocked as destruction
180  * of the interpreter can lead to recursive destruction calls that could
181  * lead to a deadlock on that mutex.
182  */
183 STATIC void
184 S_ithread_clear(pTHX_ ithread *thread)
185 {
186     PerlInterpreter *interp;
187 #ifndef WIN32
188     sigset_t origmask;
189 #endif
190
191     assert(((thread->state & PERL_ITHR_FINISHED) &&
192             (thread->state & PERL_ITHR_UNCALLABLE))
193                 ||
194            (thread->state & PERL_ITHR_NONVIABLE));
195
196 #ifndef WIN32
197     /* We temporarily set the interpreter context to the interpreter being
198      * destroyed.  It's in no condition to handle signals while it's being
199      * taken apart.
200      */
201     S_block_most_signals(&origmask);
202 #endif
203
204     interp = thread->interp;
205     if (interp) {
206         dTHXa(interp);
207
208         PERL_SET_CONTEXT(interp);
209         S_ithread_set(aTHX_ thread);
210
211         SvREFCNT_dec(thread->params);
212         thread->params = Nullsv;
213
214         if (thread->err) {
215             SvREFCNT_dec(thread->err);
216             thread->err = Nullsv;
217         }
218
219         perl_destruct(interp);
220         perl_free(interp);
221         thread->interp = NULL;
222     }
223
224     PERL_SET_CONTEXT(aTHX);
225 #ifndef WIN32
226     S_set_sigmask(&origmask);
227 #endif
228 }
229
230
231 /* Decrement the refcount of an ithread, and if it reaches zero, free it.
232  * Must be called with the mutex held.
233  * On return, mutex is released (or destroyed).
234  */
235 STATIC void
236 S_ithread_free(pTHX_ ithread *thread)
237 {
238 #ifdef WIN32
239     HANDLE handle;
240 #endif
241     dMY_POOL;
242
243     if (! (thread->state & PERL_ITHR_NONVIABLE)) {
244         assert(thread->count > 0);
245         if (--thread->count > 0) {
246             MUTEX_UNLOCK(&thread->mutex);
247             return;
248         }
249         assert((thread->state & PERL_ITHR_FINISHED) &&
250                (thread->state & PERL_ITHR_UNCALLABLE));
251     }
252     MUTEX_UNLOCK(&thread->mutex);
253
254     /* Main thread (0) is immortal and should never get here */
255     assert(thread->tid != 0);
256
257     /* Remove from circular list of threads */
258     MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
259     assert(thread->prev && thread->next);
260     thread->next->prev = thread->prev;
261     thread->prev->next = thread->next;
262     thread->next = NULL;
263     thread->prev = NULL;
264     MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
265
266     /* Thread is now disowned */
267     MUTEX_LOCK(&thread->mutex);
268     S_ithread_clear(aTHX_ thread);
269
270 #ifdef WIN32
271     handle = thread->handle;
272     thread->handle = NULL;
273 #endif
274     MUTEX_UNLOCK(&thread->mutex);
275     MUTEX_DESTROY(&thread->mutex);
276
277 #ifdef WIN32
278     if (handle) {
279         CloseHandle(handle);
280     }
281 #endif
282
283     PerlMemShared_free(thread);
284
285     /* total_threads >= 1 is used to veto cleanup by the main thread,
286      * should it happen to exit while other threads still exist.
287      * Decrement this as the very last thing in the thread's existence.
288      * Otherwise, MY_POOL and global state such as PL_op_mutex may get
289      * freed while we're still using it.
290      */
291     MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
292     MY_POOL.total_threads--;
293     MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
294 }
295
296
297 static void
298 S_ithread_count_inc(pTHX_ ithread *thread)
299 {
300     MUTEX_LOCK(&thread->mutex);
301     thread->count++;
302     MUTEX_UNLOCK(&thread->mutex);
303 }
304
305
306 /* Warn if exiting with any unjoined threads */
307 STATIC int
308 S_exit_warning(pTHX)
309 {
310     int veto_cleanup, warn;
311     dMY_POOL;
312
313     MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
314     veto_cleanup = (MY_POOL.total_threads > 0);
315     warn         = (MY_POOL.running_threads || MY_POOL.joinable_threads);
316     MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
317
318     if (warn) {
319         if (ckWARN_d(WARN_THREADS)) {
320             Perl_warn(aTHX_ "Perl exited with active threads:\n\t%"
321                             IVdf " running and unjoined\n\t%"
322                             IVdf " finished and unjoined\n\t%"
323                             IVdf " running and detached\n",
324                             MY_POOL.running_threads,
325                             MY_POOL.joinable_threads,
326                             MY_POOL.detached_threads);
327         }
328     }
329
330     return (veto_cleanup);
331 }
332
333
334 /* Called from perl_destruct() in each thread.  If it's the main thread,
335  * stop it from freeing everything if there are other threads still running.
336  */
337 int
338 Perl_ithread_hook(pTHX)
339 {
340     dMY_POOL;
341     return ((aTHX == MY_POOL.main_thread.interp) ? S_exit_warning(aTHX) : 0);
342 }
343
344
345 /* MAGIC (in mg.h sense) hooks */
346
347 int
348 ithread_mg_get(pTHX_ SV *sv, MAGIC *mg)
349 {
350     ithread *thread = (ithread *)mg->mg_ptr;
351     SvIV_set(sv, PTR2IV(thread));
352     SvIOK_on(sv);
353     return (0);
354 }
355
356 int
357 ithread_mg_free(pTHX_ SV *sv, MAGIC *mg)
358 {
359     ithread *thread = (ithread *)mg->mg_ptr;
360     MUTEX_LOCK(&thread->mutex);
361     S_ithread_free(aTHX_ thread);   /* Releases MUTEX */
362     return (0);
363 }
364
365 int
366 ithread_mg_dup(pTHX_ MAGIC *mg, CLONE_PARAMS *param)
367 {
368     S_ithread_count_inc(aTHX_ (ithread *)mg->mg_ptr);
369     return (0);
370 }
371
372 MGVTBL ithread_vtbl = {
373     ithread_mg_get,     /* get */
374     0,                  /* set */
375     0,                  /* len */
376     0,                  /* clear */
377     ithread_mg_free,    /* free */
378     0,                  /* copy */
379     ithread_mg_dup      /* dup */
380 };
381
382
383 /* Provided default, minimum and rational stack sizes */
384 STATIC IV
385 S_good_stack_size(pTHX_ IV stack_size)
386 {
387     dMY_POOL;
388
389     /* Use default stack size if no stack size specified */
390     if (! stack_size) {
391         return (MY_POOL.default_stack_size);
392     }
393
394 #ifdef PTHREAD_STACK_MIN
395     /* Can't use less than minimum */
396     if (stack_size < PTHREAD_STACK_MIN) {
397         if (ckWARN(WARN_THREADS)) {
398             Perl_warn(aTHX_ "Using minimum thread stack size of %" IVdf, (IV)PTHREAD_STACK_MIN);
399         }
400         return (PTHREAD_STACK_MIN);
401     }
402 #endif
403
404     /* Round up to page size boundary */
405     if (MY_POOL.page_size <= 0) {
406 #if defined(HAS_SYSCONF) && (defined(_SC_PAGESIZE) || defined(_SC_MMAP_PAGE_SIZE))
407         SETERRNO(0, SS_NORMAL);
408 #  ifdef _SC_PAGESIZE
409         MY_POOL.page_size = sysconf(_SC_PAGESIZE);
410 #  else
411         MY_POOL.page_size = sysconf(_SC_MMAP_PAGE_SIZE);
412 #  endif
413         if ((long)MY_POOL.page_size < 0) {
414             if (errno) {
415                 SV * const error = get_sv("@", 0);
416                 (void)SvUPGRADE(error, SVt_PV);
417                 Perl_croak(aTHX_ "PANIC: sysconf: %s", SvPV_nolen(error));
418             } else {
419                 Perl_croak(aTHX_ "PANIC: sysconf: pagesize unknown");
420             }
421         }
422 #else
423 #  ifdef HAS_GETPAGESIZE
424         MY_POOL.page_size = getpagesize();
425 #  else
426 #    if defined(I_SYS_PARAM) && defined(PAGESIZE)
427         MY_POOL.page_size = PAGESIZE;
428 #    else
429         MY_POOL.page_size = 8192;   /* A conservative default */
430 #    endif
431 #  endif
432         if (MY_POOL.page_size <= 0) {
433             Perl_croak(aTHX_ "PANIC: bad pagesize %" IVdf, (IV)MY_POOL.page_size);
434         }
435 #endif
436     }
437     stack_size = ((stack_size + (MY_POOL.page_size - 1)) / MY_POOL.page_size) * MY_POOL.page_size;
438
439     return (stack_size);
440 }
441
442
443 /* Starts executing the thread.
444  * Passed as the C level function to run in the new thread.
445  */
446 #ifdef WIN32
447 STATIC THREAD_RET_TYPE
448 S_ithread_run(LPVOID arg)
449 #else
450 STATIC void *
451 S_ithread_run(void * arg)
452 #endif
453 {
454     ithread *thread = (ithread *)arg;
455     int jmp_rc = 0;
456     I32 oldscope;
457     int exit_app = 0;   /* Thread terminated using 'exit' */
458     int exit_code = 0;
459     int died = 0;       /* Thread terminated abnormally */
460
461     dJMPENV;
462
463     dTHXa(thread->interp);
464
465     dMY_POOL;
466
467     /* Blocked until ->create() call finishes */
468     MUTEX_LOCK(&thread->mutex);
469     MUTEX_UNLOCK(&thread->mutex);
470
471     PERL_SET_CONTEXT(thread->interp);
472     S_ithread_set(aTHX_ thread);
473
474 #ifndef WIN32
475     /* Thread starts with most signals blocked - restore the signal mask from
476      * the ithread struct.
477      */
478     S_set_sigmask(&thread->initial_sigmask);
479 #endif
480
481     PL_perl_destruct_level = 2;
482
483     {
484         AV *params = (AV *)SvRV(thread->params);
485         int len = (int)av_len(params)+1;
486         int ii;
487
488         dSP;
489         ENTER;
490         SAVETMPS;
491
492         /* Put args on the stack */
493         PUSHMARK(SP);
494         for (ii=0; ii < len; ii++) {
495             XPUSHs(av_shift(params));
496         }
497         PUTBACK;
498
499         oldscope = PL_scopestack_ix;
500         JMPENV_PUSH(jmp_rc);
501         if (jmp_rc == 0) {
502             /* Run the specified function */
503             len = (int)call_sv(thread->init_function, thread->gimme|G_EVAL);
504         } else if (jmp_rc == 2) {
505             /* Thread exited */
506             exit_app = 1;
507             exit_code = STATUS_CURRENT;
508             while (PL_scopestack_ix > oldscope) {
509                 LEAVE;
510             }
511         }
512         JMPENV_POP;
513
514 #ifndef WIN32
515         /* The interpreter is finished, so this thread can stop receiving
516          * signals.  This way, our signal handler doesn't get called in the
517          * middle of our parent thread calling perl_destruct()...
518          */
519         S_block_most_signals(NULL);
520 #endif
521
522         /* Remove args from stack and put back in params array */
523         SPAGAIN;
524         for (ii=len-1; ii >= 0; ii--) {
525             SV *sv = POPs;
526             if (jmp_rc == 0 && (thread->gimme & G_WANT) != G_VOID) {
527                 av_store(params, ii, SvREFCNT_inc(sv));
528             }
529         }
530
531         FREETMPS;
532         LEAVE;
533
534         /* Check for abnormal termination */
535         if (SvTRUE(ERRSV)) {
536             died = PERL_ITHR_DIED;
537             thread->err = newSVsv(ERRSV);
538             /* If ERRSV is an object, remember the classname and then
539              * rebless into 'main' so it will survive 'cloning'
540              */
541             if (sv_isobject(thread->err)) {
542                 thread->err_class = HvNAME(SvSTASH(SvRV(thread->err)));
543                 sv_bless(thread->err, gv_stashpv("main", 0));
544             }
545
546             if (ckWARN_d(WARN_THREADS)) {
547                 oldscope = PL_scopestack_ix;
548                 JMPENV_PUSH(jmp_rc);
549                 if (jmp_rc == 0) {
550                     /* Warn that thread died */
551                     Perl_warn(aTHX_ "Thread %" UVuf " terminated abnormally: %" SVf, thread->tid, ERRSV);
552                 } else if (jmp_rc == 2) {
553                     /* Warn handler exited */
554                     exit_app = 1;
555                     exit_code = STATUS_CURRENT;
556                     while (PL_scopestack_ix > oldscope) {
557                         LEAVE;
558                     }
559                 }
560                 JMPENV_POP;
561             }
562         }
563
564         /* Release function ref */
565         SvREFCNT_dec(thread->init_function);
566         thread->init_function = Nullsv;
567     }
568
569     PerlIO_flush((PerlIO *)NULL);
570
571     MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
572     MUTEX_LOCK(&thread->mutex);
573     /* Mark as finished */
574     thread->state |= (PERL_ITHR_FINISHED | died);
575     /* Clear exit flag if required */
576     if (thread->state & PERL_ITHR_THREAD_EXIT_ONLY) {
577         exit_app = 0;
578     }
579
580     /* Adjust thread status counts */
581     if (thread->state & PERL_ITHR_DETACHED) {
582         MY_POOL.detached_threads--;
583     } else {
584         MY_POOL.running_threads--;
585         MY_POOL.joinable_threads++;
586     }
587     MUTEX_UNLOCK(&thread->mutex);
588     MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
589
590     /* Exit application if required */
591     if (exit_app) {
592         oldscope = PL_scopestack_ix;
593         JMPENV_PUSH(jmp_rc);
594         if (jmp_rc == 0) {
595             /* Warn if there are unjoined threads */
596             S_exit_warning(aTHX);
597         } else if (jmp_rc == 2) {
598             /* Warn handler exited */
599             exit_code = STATUS_CURRENT;
600             while (PL_scopestack_ix > oldscope) {
601                 LEAVE;
602             }
603         }
604         JMPENV_POP;
605
606         my_exit(exit_code);
607     }
608
609     /* At this point, the interpreter may have been freed, so call
610      * free in the the context of of the 'main' interpreter which
611      * can't have been freed due to the veto_cleanup mechanism.
612      */
613     aTHX = MY_POOL.main_thread.interp;
614
615     MUTEX_LOCK(&thread->mutex);
616     S_ithread_free(aTHX_ thread);   /* Releases MUTEX */
617
618 #ifdef WIN32
619     return ((DWORD)0);
620 #else
621     return (0);
622 #endif
623 }
624
625
626 /* Type conversion helper functions */
627
628 STATIC SV *
629 S_ithread_to_SV(pTHX_ SV *obj, ithread *thread, char *classname, bool inc)
630 {
631     SV *sv;
632     MAGIC *mg;
633
634     if (inc)
635         S_ithread_count_inc(aTHX_ thread);
636
637     if (! obj) {
638         obj = newSV(0);
639     }
640
641     sv = newSVrv(obj, classname);
642     sv_setiv(sv, PTR2IV(thread));
643     mg = sv_magicext(sv, Nullsv, PERL_MAGIC_shared_scalar, &ithread_vtbl, (char *)thread, 0);
644     mg->mg_flags |= MGf_DUP;
645     SvREADONLY_on(sv);
646
647     return (obj);
648 }
649
650 STATIC ithread *
651 S_SV_to_ithread(pTHX_ SV *sv)
652 {
653     /* Argument is a thread */
654     if (SvROK(sv)) {
655       return (INT2PTR(ithread *, SvIV(SvRV(sv))));
656     }
657     /* Argument is classname, therefore return current thread */
658     return (S_ithread_get(aTHX));
659 }
660
661
662 /* threads->create()
663  * Called in context of parent thread.
664  * Called with MY_POOL.create_destruct_mutex locked.  (Unlocked on error.)
665  */
666 STATIC ithread *
667 S_ithread_create(
668         pTHX_ SV *init_function,
669         IV        stack_size,
670         int       gimme,
671         int       exit_opt,
672         SV       *params)
673 {
674     ithread     *thread;
675     ithread     *current_thread = S_ithread_get(aTHX);
676
677     SV         **tmps_tmp = PL_tmps_stack;
678     IV           tmps_ix  = PL_tmps_ix;
679 #ifndef WIN32
680     int          rc_stack_size = 0;
681     int          rc_thread_create = 0;
682 #endif
683     dMY_POOL;
684
685     /* Allocate thread structure in context of the main thread's interpreter */
686     {
687         PERL_SET_CONTEXT(MY_POOL.main_thread.interp);
688         thread = (ithread *)PerlMemShared_malloc(sizeof(ithread));
689     }
690     PERL_SET_CONTEXT(aTHX);
691     if (!thread) {
692         MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
693         PerlLIO_write(PerlIO_fileno(Perl_error_log), PL_no_mem, strlen(PL_no_mem));
694         my_exit(1);
695     }
696     Zero(thread, 1, ithread);
697
698     /* Add to threads list */
699     thread->next = &MY_POOL.main_thread;
700     thread->prev = MY_POOL.main_thread.prev;
701     MY_POOL.main_thread.prev = thread;
702     thread->prev->next = thread;
703     MY_POOL.total_threads++;
704
705     /* 1 ref to be held by the local var 'thread' in S_ithread_run().
706      * 1 ref to be held by the threads object that we assume we will
707      *      be embedded in upon our return.
708      * 1 ref to be the responsibility of join/detach, so we don't get
709      *      freed until join/detach, even if no thread objects remain.
710      *      This allows the following to work:
711      *          { threads->create(sub{...}); } threads->object(1)->join;
712      */
713     thread->count = 3;
714
715     /* Block new thread until ->create() call finishes */
716     MUTEX_INIT(&thread->mutex);
717     MUTEX_LOCK(&thread->mutex);
718
719     thread->tid = MY_POOL.tid_counter++;
720     thread->stack_size = S_good_stack_size(aTHX_ stack_size);
721     thread->gimme = gimme;
722     thread->state = exit_opt;
723
724     /* "Clone" our interpreter into the thread's interpreter.
725      * This gives thread access to "static data" and code.
726      */
727     PerlIO_flush((PerlIO *)NULL);
728     S_ithread_set(aTHX_ thread);
729
730     SAVEBOOL(PL_srand_called); /* Save this so it becomes the correct value */
731     PL_srand_called = FALSE;   /* Set it to false so we can detect if it gets
732                                   set during the clone */
733
734 #ifndef WIN32
735     /* perl_clone() will leave us the new interpreter's context.  This poses
736      * two problems for our signal handler.  First, it sets the new context
737      * before the new interpreter struct is fully initialized, so our signal
738      * handler might find bogus data in the interpreter struct it gets.
739      * Second, even if the interpreter is initialized before a signal comes in,
740      * we would like to avoid that interpreter receiving notifications for
741      * signals (especially when they ought to be for the one running in this
742      * thread), until it is running in its own thread.  Another problem is that
743      * the new thread will not have set the context until some time after it
744      * has started, so it won't be safe for our signal handler to run until
745      * that time.
746      *
747      * So we block most signals here, so the new thread will inherit the signal
748      * mask, and unblock them right after the thread creation.  The original
749      * mask is saved in the thread struct so that the new thread can restore
750      * the original mask.
751      */
752     S_block_most_signals(&thread->initial_sigmask);
753 #endif
754
755 #ifdef WIN32
756     thread->interp = perl_clone(aTHX, CLONEf_KEEP_PTR_TABLE | CLONEf_CLONE_HOST);
757 #else
758     thread->interp = perl_clone(aTHX, CLONEf_KEEP_PTR_TABLE);
759 #endif
760
761     /* perl_clone() leaves us in new interpreter's context.  As it is tricky
762      * to spot an implicit aTHX, create a new scope with aTHX matching the
763      * context for the duration of our work for new interpreter.
764      */
765     {
766         CLONE_PARAMS clone_param;
767
768         dTHXa(thread->interp);
769
770         MY_CXT_CLONE;
771
772         /* Here we remove END blocks since they should only run in the thread
773          * they are created
774          */
775         SvREFCNT_dec(PL_endav);
776         PL_endav = newAV();
777
778         clone_param.flags = 0;
779         if (SvPOK(init_function)) {
780             thread->init_function = newSV(0);
781             sv_copypv(thread->init_function, init_function);
782         } else {
783             thread->init_function =
784                 SvREFCNT_inc(sv_dup(init_function, &clone_param));
785         }
786
787         thread->params = sv_dup(params, &clone_param);
788         SvREFCNT_inc_void(thread->params);
789
790         /* The code below checks that anything living on the tmps stack and
791          * has been cloned (so it lives in the ptr_table) has a refcount
792          * higher than 0.
793          *
794          * If the refcount is 0 it means that a something on the stack/context
795          * was holding a reference to it and since we init_stacks() in
796          * perl_clone that won't get cleaned and we will get a leaked scalar.
797          * The reason it was cloned was that it lived on the @_ stack.
798          *
799          * Example of this can be found in bugreport 15837 where calls in the
800          * parameter list end up as a temp.
801          *
802          * One could argue that this fix should be in perl_clone.
803          */
804         while (tmps_ix > 0) {
805             SV* sv = (SV*)ptr_table_fetch(PL_ptr_table, tmps_tmp[tmps_ix]);
806             tmps_ix--;
807             if (sv && SvREFCNT(sv) == 0) {
808                 SvREFCNT_inc_void(sv);
809                 SvREFCNT_dec(sv);
810             }
811         }
812
813         SvTEMP_off(thread->init_function);
814         ptr_table_free(PL_ptr_table);
815         PL_ptr_table = NULL;
816         PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
817     }
818     S_ithread_set(aTHX_ current_thread);
819     PERL_SET_CONTEXT(aTHX);
820
821     /* Create/start the thread */
822 #ifdef WIN32
823     thread->handle = CreateThread(NULL,
824                                   (DWORD)thread->stack_size,
825                                   S_ithread_run,
826                                   (LPVOID)thread,
827                                   STACK_SIZE_PARAM_IS_A_RESERVATION,
828                                   &thread->thr);
829 #else
830     {
831         STATIC pthread_attr_t attr;
832         STATIC int attr_inited = 0;
833         STATIC int attr_joinable = PTHREAD_CREATE_JOINABLE;
834         if (! attr_inited) {
835             pthread_attr_init(&attr);
836             attr_inited = 1;
837         }
838
839 #  ifdef PTHREAD_ATTR_SETDETACHSTATE
840         /* Threads start out joinable */
841         PTHREAD_ATTR_SETDETACHSTATE(&attr, attr_joinable);
842 #  endif
843
844 #  ifdef _POSIX_THREAD_ATTR_STACKSIZE
845         /* Set thread's stack size */
846         if (thread->stack_size > 0) {
847             rc_stack_size = pthread_attr_setstacksize(&attr, (size_t)thread->stack_size);
848         }
849 #  endif
850
851         /* Create the thread */
852         if (! rc_stack_size) {
853 #  ifdef OLD_PTHREADS_API
854             rc_thread_create = pthread_create(&thread->thr,
855                                               attr,
856                                               S_ithread_run,
857                                               (void *)thread);
858 #  else
859 #    if defined(HAS_PTHREAD_ATTR_SETSCOPE) && defined(PTHREAD_SCOPE_SYSTEM)
860             pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);
861 #    endif
862             rc_thread_create = pthread_create(&thread->thr,
863                                               &attr,
864                                               S_ithread_run,
865                                               (void *)thread);
866 #  endif
867         }
868
869 #ifndef WIN32
870     /* Now it's safe to accept signals, since we're in our own interpreter's
871      * context and we have created the thread.
872      */
873     S_set_sigmask(&thread->initial_sigmask);
874 #endif
875
876 #  ifdef _POSIX_THREAD_ATTR_STACKSIZE
877         /* Try to get thread's actual stack size */
878         {
879             size_t stacksize;
880 #ifdef HPUX1020
881             stacksize = pthread_attr_getstacksize(attr);
882 #else
883             if (! pthread_attr_getstacksize(&attr, &stacksize))
884 #endif
885                 if (stacksize > 0) {
886                     thread->stack_size = (IV)stacksize;
887                 }
888         }
889 #  endif
890     }
891 #endif
892
893     /* Check for errors */
894 #ifdef WIN32
895     if (thread->handle == NULL) {
896 #else
897     if (rc_stack_size || rc_thread_create) {
898 #endif
899         /* Must unlock mutex for destruct call */
900         MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
901         sv_2mortal(params);
902         thread->state |= PERL_ITHR_NONVIABLE;
903         S_ithread_free(aTHX_ thread);   /* Releases MUTEX */
904 #ifndef WIN32
905         if (ckWARN_d(WARN_THREADS)) {
906             if (rc_stack_size) {
907                 Perl_warn(aTHX_ "Thread creation failed: pthread_attr_setstacksize(%" IVdf ") returned %d", thread->stack_size, rc_stack_size);
908             } else {
909                 Perl_warn(aTHX_ "Thread creation failed: pthread_create returned %d", rc_thread_create);
910             }
911         }
912 #endif
913         return (NULL);
914     }
915
916     MY_POOL.running_threads++;
917     sv_2mortal(params);
918     return (thread);
919 }
920
921 #endif /* USE_ITHREADS */
922
923
924 MODULE = threads    PACKAGE = threads    PREFIX = ithread_
925 PROTOTYPES: DISABLE
926
927 #ifdef USE_ITHREADS
928
929 void
930 ithread_create(...)
931     PREINIT:
932         char *classname;
933         ithread *thread;
934         SV *function_to_call;
935         AV *params;
936         HV *specs;
937         IV stack_size;
938         int context;
939         int exit_opt;
940         SV *thread_exit_only;
941         char *str;
942         int idx;
943         int ii;
944         dMY_POOL;
945     CODE:
946         if ((items >= 2) && SvROK(ST(1)) && SvTYPE(SvRV(ST(1)))==SVt_PVHV) {
947             if (--items < 2) {
948                 Perl_croak(aTHX_ "Usage: threads->create(\\%%specs, function, ...)");
949             }
950             specs = (HV*)SvRV(ST(1));
951             idx = 1;
952         } else {
953             if (items < 2) {
954                 Perl_croak(aTHX_ "Usage: threads->create(function, ...)");
955             }
956             specs = NULL;
957             idx = 0;
958         }
959
960         if (sv_isobject(ST(0))) {
961             /* $thr->create() */
962             classname = HvNAME(SvSTASH(SvRV(ST(0))));
963             thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
964             MUTEX_LOCK(&thread->mutex);
965             stack_size = thread->stack_size;
966             exit_opt = thread->state & PERL_ITHR_THREAD_EXIT_ONLY;
967             MUTEX_UNLOCK(&thread->mutex);
968         } else {
969             /* threads->create() */
970             classname = (char *)SvPV_nolen(ST(0));
971             stack_size = MY_POOL.default_stack_size;
972             thread_exit_only = get_sv("threads::thread_exit_only", GV_ADD);
973             exit_opt = (SvTRUE(thread_exit_only))
974                                     ? PERL_ITHR_THREAD_EXIT_ONLY : 0;
975         }
976
977         function_to_call = ST(idx+1);
978
979         context = -1;
980         if (specs) {
981             /* stack_size */
982             if (hv_exists(specs, "stack", 5)) {
983                 stack_size = SvIV(*hv_fetch(specs, "stack", 5, 0));
984             } else if (hv_exists(specs, "stacksize", 9)) {
985                 stack_size = SvIV(*hv_fetch(specs, "stacksize", 9, 0));
986             } else if (hv_exists(specs, "stack_size", 10)) {
987                 stack_size = SvIV(*hv_fetch(specs, "stack_size", 10, 0));
988             }
989
990             /* context */
991             if (hv_exists(specs, "context", 7)) {
992                 str = (char *)SvPV_nolen(*hv_fetch(specs, "context", 7, 0));
993                 switch (*str) {
994                     case 'a':
995                     case 'A':
996                     case 'l':
997                     case 'L':
998                         context = G_ARRAY;
999                         break;
1000                     case 's':
1001                     case 'S':
1002                         context = G_SCALAR;
1003                         break;
1004                     case 'v':
1005                     case 'V':
1006                         context = G_VOID;
1007                         break;
1008                     default:
1009                         Perl_croak(aTHX_ "Invalid context: %s", str);
1010                 }
1011             } else if (hv_exists(specs, "array", 5)) {
1012                 if (SvTRUE(*hv_fetch(specs, "array", 5, 0))) {
1013                     context = G_ARRAY;
1014                 }
1015             } else if (hv_exists(specs, "list", 4)) {
1016                 if (SvTRUE(*hv_fetch(specs, "list", 4, 0))) {
1017                     context = G_ARRAY;
1018                 }
1019             } else if (hv_exists(specs, "scalar", 6)) {
1020                 if (SvTRUE(*hv_fetch(specs, "scalar", 6, 0))) {
1021                     context = G_SCALAR;
1022                 }
1023             } else if (hv_exists(specs, "void", 4)) {
1024                 if (SvTRUE(*hv_fetch(specs, "void", 4, 0))) {
1025                     context = G_VOID;
1026                 }
1027             }
1028
1029             /* exit => thread_only */
1030             if (hv_exists(specs, "exit", 4)) {
1031                 str = (char *)SvPV_nolen(*hv_fetch(specs, "exit", 4, 0));
1032                 exit_opt = (*str == 't' || *str == 'T')
1033                                     ? PERL_ITHR_THREAD_EXIT_ONLY : 0;
1034             }
1035         }
1036         if (context == -1) {
1037             context = GIMME_V;  /* Implicit context */
1038         } else {
1039             context |= (GIMME_V & (~(G_ARRAY|G_SCALAR|G_VOID)));
1040         }
1041
1042         /* Function args */
1043         params = newAV();
1044         if (items > 2) {
1045             for (ii=2; ii < items ; ii++) {
1046                 av_push(params, SvREFCNT_inc(ST(idx+ii)));
1047             }
1048         }
1049
1050         /* Create thread */
1051         MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
1052         thread = S_ithread_create(aTHX_ function_to_call,
1053                                         stack_size,
1054                                         context,
1055                                         exit_opt,
1056                                         newRV_noinc((SV*)params));
1057         if (! thread) {
1058             XSRETURN_UNDEF;     /* Mutex already unlocked */
1059         }
1060         ST(0) = sv_2mortal(S_ithread_to_SV(aTHX_ Nullsv, thread, classname, FALSE));
1061         MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
1062
1063         /* Let thread run */
1064         MUTEX_UNLOCK(&thread->mutex);
1065
1066         /* XSRETURN(1); - implied */
1067
1068
1069 void
1070 ithread_list(...)
1071     PREINIT:
1072         char *classname;
1073         ithread *thread;
1074         int list_context;
1075         IV count = 0;
1076         int want_running = 0;
1077         int state;
1078         dMY_POOL;
1079     PPCODE:
1080         /* Class method only */
1081         if (SvROK(ST(0))) {
1082             Perl_croak(aTHX_ "Usage: threads->list(...)");
1083         }
1084         classname = (char *)SvPV_nolen(ST(0));
1085
1086         /* Calling context */
1087         list_context = (GIMME_V == G_ARRAY);
1088
1089         /* Running or joinable parameter */
1090         if (items > 1) {
1091             want_running = SvTRUE(ST(1));
1092         }
1093
1094         /* Walk through threads list */
1095         MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
1096         for (thread = MY_POOL.main_thread.next;
1097              thread != &MY_POOL.main_thread;
1098              thread = thread->next)
1099         {
1100             MUTEX_LOCK(&thread->mutex);
1101             state = thread->state;
1102             MUTEX_UNLOCK(&thread->mutex);
1103
1104             /* Ignore detached or joined threads */
1105             if (state & PERL_ITHR_UNCALLABLE) {
1106                 continue;
1107             }
1108
1109             /* Filter per parameter */
1110             if (items > 1) {
1111                 if (want_running) {
1112                     if (state & PERL_ITHR_FINISHED) {
1113                         continue;   /* Not running */
1114                     }
1115                 } else {
1116                     if (! (state & PERL_ITHR_FINISHED)) {
1117                         continue;   /* Still running - not joinable yet */
1118                     }
1119                 }
1120             }
1121
1122             /* Push object on stack if list context */
1123             if (list_context) {
1124                 XPUSHs(sv_2mortal(S_ithread_to_SV(aTHX_ Nullsv, thread, classname, TRUE)));
1125             }
1126             count++;
1127         }
1128         MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
1129         /* If scalar context, send back count */
1130         if (! list_context) {
1131             XSRETURN_IV(count);
1132         }
1133
1134
1135 void
1136 ithread_self(...)
1137     PREINIT:
1138         char *classname;
1139         ithread *thread;
1140     CODE:
1141         /* Class method only */
1142         if ((items != 1) || SvROK(ST(0))) {
1143             Perl_croak(aTHX_ "Usage: threads->self()");
1144         }
1145         classname = (char *)SvPV_nolen(ST(0));
1146
1147         thread = S_ithread_get(aTHX);
1148
1149         ST(0) = sv_2mortal(S_ithread_to_SV(aTHX_ Nullsv, thread, classname, TRUE));
1150         /* XSRETURN(1); - implied */
1151
1152
1153 void
1154 ithread_tid(...)
1155     PREINIT:
1156         ithread *thread;
1157     CODE:
1158         PERL_UNUSED_VAR(items);
1159         thread = S_SV_to_ithread(aTHX_ ST(0));
1160         XST_mUV(0, thread->tid);
1161         /* XSRETURN(1); - implied */
1162
1163
1164 void
1165 ithread_join(...)
1166     PREINIT:
1167         ithread *thread;
1168         ithread *current_thread;
1169         int join_err;
1170         AV *params = NULL;
1171         int len;
1172         int ii;
1173 #ifndef WIN32
1174         int rc_join;
1175         void *retval;
1176 #endif
1177         dMY_POOL;
1178     PPCODE:
1179         /* Object method only */
1180         if ((items != 1) || ! sv_isobject(ST(0))) {
1181             Perl_croak(aTHX_ "Usage: $thr->join()");
1182         }
1183
1184         /* Check if the thread is joinable and not ourselves */
1185         thread = S_SV_to_ithread(aTHX_ ST(0));
1186         current_thread = S_ithread_get(aTHX);
1187
1188         MUTEX_LOCK(&thread->mutex);
1189         if ((join_err = (thread->state & PERL_ITHR_UNCALLABLE))) {
1190             MUTEX_UNLOCK(&thread->mutex);
1191             Perl_croak(aTHX_ (join_err & PERL_ITHR_DETACHED)
1192                                 ? "Cannot join a detached thread"
1193                                 : "Thread already joined");
1194         } else if (thread->tid == current_thread->tid) {
1195             MUTEX_UNLOCK(&thread->mutex);
1196             Perl_croak(aTHX_ "Cannot join self");
1197         }
1198
1199         /* Mark as joined */
1200         thread->state |= PERL_ITHR_JOINED;
1201         MUTEX_UNLOCK(&thread->mutex);
1202
1203         MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
1204         MY_POOL.joinable_threads--;
1205         MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
1206
1207         /* Join the thread */
1208 #ifdef WIN32
1209         if (WaitForSingleObject(thread->handle, INFINITE) != WAIT_OBJECT_0) {
1210             /* Timeout/abandonment unexpected here; check $^E */
1211             Perl_croak(aTHX_ "PANIC: underlying join failed");
1212         };
1213 #else
1214         if ((rc_join = pthread_join(thread->thr, &retval)) != 0) {
1215             /* In progress/deadlock/unknown unexpected here; check $! */
1216             errno = rc_join;
1217             Perl_croak(aTHX_ "PANIC: underlying join failed");
1218         };
1219 #endif
1220
1221         MUTEX_LOCK(&thread->mutex);
1222         /* Get the return value from the call_sv */
1223         /* Objects do not survive this process - FIXME */
1224         if ((thread->gimme & G_WANT) != G_VOID) {
1225             AV *params_copy;
1226             PerlInterpreter *other_perl;
1227             CLONE_PARAMS clone_params;
1228
1229             params_copy = (AV *)SvRV(thread->params);
1230             other_perl = thread->interp;
1231             clone_params.stashes = newAV();
1232             clone_params.flags = CLONEf_JOIN_IN;
1233             PL_ptr_table = ptr_table_new();
1234             S_ithread_set(aTHX_ thread);
1235             /* Ensure 'meaningful' addresses retain their meaning */
1236             ptr_table_store(PL_ptr_table, &other_perl->Isv_undef, &PL_sv_undef);
1237             ptr_table_store(PL_ptr_table, &other_perl->Isv_no, &PL_sv_no);
1238             ptr_table_store(PL_ptr_table, &other_perl->Isv_yes, &PL_sv_yes);
1239             params = (AV *)sv_dup((SV*)params_copy, &clone_params);
1240             S_ithread_set(aTHX_ current_thread);
1241             SvREFCNT_dec(clone_params.stashes);
1242             SvREFCNT_inc_void(params);
1243             ptr_table_free(PL_ptr_table);
1244             PL_ptr_table = NULL;
1245         }
1246
1247         /* If thread didn't die, then we can free its interpreter */
1248         if (! (thread->state & PERL_ITHR_DIED)) {
1249             S_ithread_clear(aTHX_ thread);
1250         }
1251         S_ithread_free(aTHX_ thread);   /* Releases MUTEX */
1252
1253         /* If no return values, then just return */
1254         if (! params) {
1255             XSRETURN_UNDEF;
1256         }
1257
1258         /* Put return values on stack */
1259         len = (int)AvFILL(params);
1260         for (ii=0; ii <= len; ii++) {
1261             SV* param = av_shift(params);
1262             XPUSHs(sv_2mortal(param));
1263         }
1264
1265         /* Free return value array */
1266         SvREFCNT_dec(params);
1267
1268
1269 void
1270 ithread_yield(...)
1271     CODE:
1272         PERL_UNUSED_VAR(items);
1273         YIELD;
1274
1275
1276 void
1277 ithread_detach(...)
1278     PREINIT:
1279         ithread *thread;
1280         int detach_err;
1281         dMY_POOL;
1282     CODE:
1283         PERL_UNUSED_VAR(items);
1284
1285         /* Detach the thread */
1286         thread = S_SV_to_ithread(aTHX_ ST(0));
1287         MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
1288         MUTEX_LOCK(&thread->mutex);
1289         if (! (detach_err = (thread->state & PERL_ITHR_UNCALLABLE))) {
1290             /* Thread is detachable */
1291             thread->state |= PERL_ITHR_DETACHED;
1292 #ifdef WIN32
1293             /* Windows has no 'detach thread' function */
1294 #else
1295             PERL_THREAD_DETACH(thread->thr);
1296 #endif
1297             if (thread->state & PERL_ITHR_FINISHED) {
1298                 MY_POOL.joinable_threads--;
1299             } else {
1300                 MY_POOL.running_threads--;
1301                 MY_POOL.detached_threads++;
1302             }
1303         }
1304         MUTEX_UNLOCK(&thread->mutex);
1305         MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
1306
1307         if (detach_err) {
1308             Perl_croak(aTHX_ (detach_err & PERL_ITHR_DETACHED)
1309                                 ? "Thread already detached"
1310                                 : "Cannot detach a joined thread");
1311         }
1312
1313         /* If thread is finished and didn't die,
1314          * then we can free its interpreter */
1315         MUTEX_LOCK(&thread->mutex);
1316         if ((thread->state & PERL_ITHR_FINISHED) &&
1317             ! (thread->state & PERL_ITHR_DIED))
1318         {
1319             S_ithread_clear(aTHX_ thread);
1320         }
1321         S_ithread_free(aTHX_ thread);   /* Releases MUTEX */
1322
1323
1324 void
1325 ithread_kill(...)
1326     PREINIT:
1327         ithread *thread;
1328         char *sig_name;
1329         IV signal;
1330     CODE:
1331         /* Must have safe signals */
1332         if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG) {
1333             Perl_croak(aTHX_ "Cannot signal threads without safe signals");
1334         }
1335
1336         /* Object method only */
1337         if ((items != 2) || ! sv_isobject(ST(0))) {
1338             Perl_croak(aTHX_ "Usage: $thr->kill('SIG...')");
1339         }
1340
1341         /* Get signal */
1342         sig_name = SvPV_nolen(ST(1));
1343         if (isALPHA(*sig_name)) {
1344             if (*sig_name == 'S' && sig_name[1] == 'I' && sig_name[2] == 'G') {
1345                 sig_name += 3;
1346             }
1347             if ((signal = whichsig(sig_name)) < 0) {
1348                 Perl_croak(aTHX_ "Unrecognized signal name: %s", sig_name);
1349             }
1350         } else {
1351             signal = SvIV(ST(1));
1352         }
1353
1354         /* Set the signal for the thread */
1355         thread = S_SV_to_ithread(aTHX_ ST(0));
1356         MUTEX_LOCK(&thread->mutex);
1357         if (thread->interp) {
1358             dTHXa(thread->interp);
1359             PL_psig_pend[signal]++;
1360             PL_sig_pending = 1;
1361         }
1362         MUTEX_UNLOCK(&thread->mutex);
1363
1364         /* Return the thread to allow for method chaining */
1365         ST(0) = ST(0);
1366         /* XSRETURN(1); - implied */
1367
1368
1369 void
1370 ithread_DESTROY(...)
1371     CODE:
1372         PERL_UNUSED_VAR(items);
1373         sv_unmagic(SvRV(ST(0)), PERL_MAGIC_shared_scalar);
1374
1375
1376 void
1377 ithread_equal(...)
1378     PREINIT:
1379         int are_equal = 0;
1380     CODE:
1381         PERL_UNUSED_VAR(items);
1382
1383         /* Compares TIDs to determine thread equality */
1384         if (sv_isobject(ST(0)) && sv_isobject(ST(1))) {
1385             ithread *thr1 = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1386             ithread *thr2 = INT2PTR(ithread *, SvIV(SvRV(ST(1))));
1387             are_equal = (thr1->tid == thr2->tid);
1388         }
1389         if (are_equal) {
1390             XST_mYES(0);
1391         } else {
1392             /* Return 0 on false for backward compatibility */
1393             XST_mIV(0, 0);
1394         }
1395         /* XSRETURN(1); - implied */
1396
1397
1398 void
1399 ithread_object(...)
1400     PREINIT:
1401         char *classname;
1402         UV tid;
1403         ithread *thread;
1404         int state;
1405         int have_obj = 0;
1406         dMY_POOL;
1407     CODE:
1408         /* Class method only */
1409         if (SvROK(ST(0))) {
1410             Perl_croak(aTHX_ "Usage: threads->object($tid)");
1411         }
1412         classname = (char *)SvPV_nolen(ST(0));
1413
1414         if ((items < 2) || ! SvOK(ST(1))) {
1415             XSRETURN_UNDEF;
1416         }
1417
1418         /* threads->object($tid) */
1419         tid = SvUV(ST(1));
1420
1421         /* Walk through threads list */
1422         MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
1423         for (thread = MY_POOL.main_thread.next;
1424              thread != &MY_POOL.main_thread;
1425              thread = thread->next)
1426         {
1427             /* Look for TID */
1428             if (thread->tid == tid) {
1429                 /* Ignore if detached or joined */
1430                 MUTEX_LOCK(&thread->mutex);
1431                 state = thread->state;
1432                 MUTEX_UNLOCK(&thread->mutex);
1433                 if (! (state & PERL_ITHR_UNCALLABLE)) {
1434                     /* Put object on stack */
1435                     ST(0) = sv_2mortal(S_ithread_to_SV(aTHX_ Nullsv, thread, classname, TRUE));
1436                     have_obj = 1;
1437                 }
1438                 break;
1439             }
1440         }
1441         MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
1442
1443         if (! have_obj) {
1444             XSRETURN_UNDEF;
1445         }
1446         /* XSRETURN(1); - implied */
1447
1448
1449 void
1450 ithread__handle(...);
1451     PREINIT:
1452         ithread *thread;
1453     CODE:
1454         PERL_UNUSED_VAR(items);
1455         thread = S_SV_to_ithread(aTHX_ ST(0));
1456 #ifdef WIN32
1457         XST_mUV(0, PTR2UV(&thread->handle));
1458 #else
1459         XST_mUV(0, PTR2UV(&thread->thr));
1460 #endif
1461         /* XSRETURN(1); - implied */
1462
1463
1464 void
1465 ithread_get_stack_size(...)
1466     PREINIT:
1467         IV stack_size;
1468         dMY_POOL;
1469     CODE:
1470         PERL_UNUSED_VAR(items);
1471         if (sv_isobject(ST(0))) {
1472             /* $thr->get_stack_size() */
1473             ithread *thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1474             stack_size = thread->stack_size;
1475         } else {
1476             /* threads->get_stack_size() */
1477             stack_size = MY_POOL.default_stack_size;
1478         }
1479         XST_mIV(0, stack_size);
1480         /* XSRETURN(1); - implied */
1481
1482
1483 void
1484 ithread_set_stack_size(...)
1485     PREINIT:
1486         IV old_size;
1487         dMY_POOL;
1488     CODE:
1489         if (items != 2) {
1490             Perl_croak(aTHX_ "Usage: threads->set_stack_size($size)");
1491         }
1492         if (sv_isobject(ST(0))) {
1493             Perl_croak(aTHX_ "Cannot change stack size of an existing thread");
1494         }
1495         if (! looks_like_number(ST(1))) {
1496             Perl_croak(aTHX_ "Stack size must be numeric");
1497         }
1498
1499         old_size = MY_POOL.default_stack_size;
1500         MY_POOL.default_stack_size = S_good_stack_size(aTHX_ SvIV(ST(1)));
1501         XST_mIV(0, old_size);
1502         /* XSRETURN(1); - implied */
1503
1504
1505 void
1506 ithread_is_running(...)
1507     PREINIT:
1508         ithread *thread;
1509     CODE:
1510         /* Object method only */
1511         if ((items != 1) || ! sv_isobject(ST(0))) {
1512             Perl_croak(aTHX_ "Usage: $thr->is_running()");
1513         }
1514
1515         thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1516         MUTEX_LOCK(&thread->mutex);
1517         ST(0) = (thread->state & PERL_ITHR_FINISHED) ? &PL_sv_no : &PL_sv_yes;
1518         MUTEX_UNLOCK(&thread->mutex);
1519         /* XSRETURN(1); - implied */
1520
1521
1522 void
1523 ithread_is_detached(...)
1524     PREINIT:
1525         ithread *thread;
1526     CODE:
1527         PERL_UNUSED_VAR(items);
1528         thread = S_SV_to_ithread(aTHX_ ST(0));
1529         MUTEX_LOCK(&thread->mutex);
1530         ST(0) = (thread->state & PERL_ITHR_DETACHED) ? &PL_sv_yes : &PL_sv_no;
1531         MUTEX_UNLOCK(&thread->mutex);
1532         /* XSRETURN(1); - implied */
1533
1534
1535 void
1536 ithread_is_joinable(...)
1537     PREINIT:
1538         ithread *thread;
1539     CODE:
1540         /* Object method only */
1541         if ((items != 1) || ! sv_isobject(ST(0))) {
1542             Perl_croak(aTHX_ "Usage: $thr->is_joinable()");
1543         }
1544
1545         thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1546         MUTEX_LOCK(&thread->mutex);
1547         ST(0) = ((thread->state & PERL_ITHR_FINISHED) &&
1548                  ! (thread->state & PERL_ITHR_UNCALLABLE))
1549             ? &PL_sv_yes : &PL_sv_no;
1550         MUTEX_UNLOCK(&thread->mutex);
1551         /* XSRETURN(1); - implied */
1552
1553
1554 void
1555 ithread_wantarray(...)
1556     PREINIT:
1557         ithread *thread;
1558     CODE:
1559         PERL_UNUSED_VAR(items);
1560         thread = S_SV_to_ithread(aTHX_ ST(0));
1561         ST(0) = ((thread->gimme & G_WANT) == G_ARRAY) ? &PL_sv_yes :
1562                 ((thread->gimme & G_WANT) == G_VOID)  ? &PL_sv_undef
1563                                        /* G_SCALAR */ : &PL_sv_no;
1564         /* XSRETURN(1); - implied */
1565
1566
1567 void
1568 ithread_set_thread_exit_only(...)
1569     PREINIT:
1570         ithread *thread;
1571     CODE:
1572         if (items != 2) {
1573             Perl_croak(aTHX_ "Usage: ->set_thread_exit_only(boolean)");
1574         }
1575         thread = S_SV_to_ithread(aTHX_ ST(0));
1576         MUTEX_LOCK(&thread->mutex);
1577         if (SvTRUE(ST(1))) {
1578             thread->state |= PERL_ITHR_THREAD_EXIT_ONLY;
1579         } else {
1580             thread->state &= ~PERL_ITHR_THREAD_EXIT_ONLY;
1581         }
1582         MUTEX_UNLOCK(&thread->mutex);
1583
1584
1585 void
1586 ithread_error(...)
1587     PREINIT:
1588         ithread *thread;
1589         SV *err = NULL;
1590     CODE:
1591         /* Object method only */
1592         if ((items != 1) || ! sv_isobject(ST(0))) {
1593             Perl_croak(aTHX_ "Usage: $thr->err()");
1594         }
1595
1596         thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1597         MUTEX_LOCK(&thread->mutex);
1598
1599         /* If thread died, then clone the error into the calling thread */
1600         if (thread->state & PERL_ITHR_DIED) {
1601             PerlInterpreter *other_perl;
1602             CLONE_PARAMS clone_params;
1603             ithread *current_thread;
1604
1605             other_perl = thread->interp;
1606             clone_params.stashes = newAV();
1607             clone_params.flags = CLONEf_JOIN_IN;
1608             PL_ptr_table = ptr_table_new();
1609             current_thread = S_ithread_get(aTHX);
1610             S_ithread_set(aTHX_ thread);
1611             /* Ensure 'meaningful' addresses retain their meaning */
1612             ptr_table_store(PL_ptr_table, &other_perl->Isv_undef, &PL_sv_undef);
1613             ptr_table_store(PL_ptr_table, &other_perl->Isv_no, &PL_sv_no);
1614             ptr_table_store(PL_ptr_table, &other_perl->Isv_yes, &PL_sv_yes);
1615             err = sv_dup(thread->err, &clone_params);
1616             S_ithread_set(aTHX_ current_thread);
1617             SvREFCNT_dec(clone_params.stashes);
1618             SvREFCNT_inc_void(err);
1619             /* If error was an object, bless it into the correct class */
1620             if (thread->err_class) {
1621                 sv_bless(err, gv_stashpv(thread->err_class, 1));
1622             }
1623             ptr_table_free(PL_ptr_table);
1624             PL_ptr_table = NULL;
1625         }
1626
1627         MUTEX_UNLOCK(&thread->mutex);
1628
1629         if (! err) {
1630             XSRETURN_UNDEF;
1631         }
1632
1633         ST(0) = sv_2mortal(err);
1634         /* XSRETURN(1); - implied */
1635
1636
1637 #endif /* USE_ITHREADS */
1638
1639
1640 BOOT:
1641 {
1642 #ifdef USE_ITHREADS
1643     SV *my_pool_sv = *hv_fetch(PL_modglobal, MY_POOL_KEY,
1644                                sizeof(MY_POOL_KEY)-1, TRUE);
1645     my_pool_t *my_poolp = (my_pool_t*)SvPVX(newSV(sizeof(my_pool_t)-1));
1646
1647     MY_CXT_INIT;
1648
1649     Zero(my_poolp, 1, my_pool_t);
1650     sv_setuv(my_pool_sv, PTR2UV(my_poolp));
1651
1652     PL_perl_destruct_level = 2;
1653     MUTEX_INIT(&MY_POOL.create_destruct_mutex);
1654     MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
1655
1656     PL_threadhook = &Perl_ithread_hook;
1657
1658     MY_POOL.tid_counter = 1;
1659 #  ifdef THREAD_CREATE_NEEDS_STACK
1660     MY_POOL.default_stack_size = THREAD_CREATE_NEEDS_STACK;
1661 #  endif
1662
1663     /* The 'main' thread is thread 0.
1664      * It is detached (unjoinable) and immortal.
1665      */
1666
1667     MUTEX_INIT(&MY_POOL.main_thread.mutex);
1668
1669     /* Head of the threads list */
1670     MY_POOL.main_thread.next = &MY_POOL.main_thread;
1671     MY_POOL.main_thread.prev = &MY_POOL.main_thread;
1672
1673     MY_POOL.main_thread.count = 1;                  /* Immortal */
1674
1675     MY_POOL.main_thread.interp = aTHX;
1676     MY_POOL.main_thread.state = PERL_ITHR_DETACHED; /* Detached */
1677     MY_POOL.main_thread.stack_size = MY_POOL.default_stack_size;
1678 #  ifdef WIN32
1679     MY_POOL.main_thread.thr = GetCurrentThreadId();
1680 #  else
1681     MY_POOL.main_thread.thr = pthread_self();
1682 #  endif
1683
1684     S_ithread_set(aTHX_ &MY_POOL.main_thread);
1685     MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
1686 #endif /* USE_ITHREADS */
1687 }