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