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