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