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
11 /* Workaround for XSUB.h bug under WIN32 */
14 # if defined(USE_NO_MINGW_SETJMP_TWO_ARGS) || (!defined(__BORLANDC__) && !defined(__MINGW64__))
15 # define setjmp(x) _setjmp(x)
17 # if defined(__MINGW64__)
18 # define setjmp(x) _setjmpex((x), mingw_getsp())
22 # define NEED_PL_signals
23 # define NEED_sv_2pv_flags
28 # define sv_dup_inc(s,t) SvREFCNT_inc(sv_dup(s,t))
30 #ifndef PERL_UNUSED_RESULT
31 # if defined(__GNUC__) && defined(HASATTRIBUTE_WARN_UNUSED_RESULT)
32 # define PERL_UNUSED_RESULT(v) STMT_START { __typeof__(v) z = (v); (void)sizeof(z); } STMT_END
34 # define PERL_UNUSED_RESULT(v) ((void)(v))
42 # define YIELD sleep(0)
46 /* Supposed to be in Winbase.h */
47 # ifndef STACK_SIZE_PARAM_IS_A_RESERVATION
48 # define STACK_SIZE_PARAM_IS_A_RESERVATION 0x00010000
50 # include <win32thread.h>
53 typedef perl_os_thread pthread_t;
58 # define PERL_THREAD_SETSPECIFIC(k,v) pthread_setspecific(k,v)
59 # ifdef OLD_PTHREADS_API
60 # define PERL_THREAD_DETACH(t) pthread_detach(&(t))
62 # define PERL_THREAD_DETACH(t) pthread_detach((t))
65 #if !defined(HAS_GETPAGESIZE) && defined(I_SYS_PARAM)
66 # include <sys/param.h>
69 /* Values for 'state' member */
70 #define PERL_ITHR_DETACHED 1 /* Thread has been detached */
71 #define PERL_ITHR_JOINED 2 /* Thread is being / has been joined */
72 #define PERL_ITHR_FINISHED 4 /* Thread has finished execution */
73 #define PERL_ITHR_THREAD_EXIT_ONLY 8 /* exit() only exits current thread */
74 #define PERL_ITHR_NONVIABLE 16 /* Thread creation failed */
75 #define PERL_ITHR_DIED 32 /* Thread finished by dying */
77 #define PERL_ITHR_UNCALLABLE (PERL_ITHR_DETACHED|PERL_ITHR_JOINED)
80 typedef struct _ithread {
81 struct _ithread *next; /* Next thread in the list */
82 struct _ithread *prev; /* Prev thread in the list */
83 PerlInterpreter *interp; /* The threads interpreter */
84 UV tid; /* Threads module's thread id */
85 perl_mutex mutex; /* Mutex for updating things in this struct */
86 int count; /* Reference count. See S_ithread_create. */
87 int state; /* Detached, joined, finished, etc. */
88 int gimme; /* Context of create */
89 SV *init_function; /* Code to run */
90 AV *params; /* Args to pass function */
92 DWORD thr; /* OS's idea if thread id */
93 HANDLE handle; /* OS's waitable handle */
95 pthread_t thr; /* OS's handle for the thread */
98 SV *err; /* Error from abnormally terminated thread */
99 char *err_class; /* Error object's classname if applicable */
101 sigset_t initial_sigmask; /* Thread wakes up with signals blocked */
106 #define MY_CXT_KEY "threads::_cxt" XS_VERSION
109 /* Used by Perl interpreter for thread context switching */
116 #define MY_POOL_KEY "threads::_pool" XS_VERSION
119 /* Structure for 'main' thread
120 * Also forms the 'base' for the doubly-linked list of threads */
123 /* Protects the creation and destruction of threads*/
124 perl_mutex create_destruct_mutex;
131 IV default_stack_size;
136 SV *my_pool_sv = *hv_fetch(PL_modglobal, MY_POOL_KEY, \
137 sizeof(MY_POOL_KEY)-1, TRUE); \
138 my_pool_t *my_poolp = INT2PTR(my_pool_t*, SvUV(my_pool_sv))
140 #define MY_POOL (*my_poolp)
142 #if defined(WIN32) || (defined(__amigaos4__) && defined(__NEWLIB__))
143 # undef THREAD_SIGNAL_BLOCKING
145 # define THREAD_SIGNAL_BLOCKING
148 #ifdef THREAD_SIGNAL_BLOCKING
150 /* Block most signals for calling thread, setting the old signal mask to
151 * oldmask, if it is not NULL */
153 S_block_most_signals(sigset_t *oldmask)
157 sigfillset(&newmask);
158 /* Don't block certain "important" signals (stolen from mg.c) */
160 sigdelset(&newmask, SIGILL);
163 sigdelset(&newmask, SIGBUS);
166 sigdelset(&newmask, SIGSEGV);
170 /* no per-thread blocking available */
171 return sigprocmask(SIG_BLOCK, &newmask, oldmask);
173 return pthread_sigmask(SIG_BLOCK, &newmask, oldmask);
177 /* Set the signal mask for this thread to newmask */
179 S_set_sigmask(sigset_t *newmask)
182 return sigprocmask(SIG_SETMASK, newmask, NULL);
184 return pthread_sigmask(SIG_SETMASK, newmask, NULL);
189 /* Used by Perl interpreter for thread context switching */
191 S_ithread_set(pTHX_ ithread *thread)
194 MY_CXT.context = thread;
201 return (MY_CXT.context);
205 /* Free any data (such as the Perl interpreter) attached to an ithread
206 * structure. This is a bit like undef on SVs, where the SV isn't freed,
207 * but the PVX is. Must be called with thread->mutex already locked. Also,
208 * must be called with MY_POOL.create_destruct_mutex unlocked as destruction
209 * of the interpreter can lead to recursive destruction calls that could
210 * lead to a deadlock on that mutex.
213 S_ithread_clear(pTHX_ ithread *thread)
215 PerlInterpreter *interp;
220 assert(((thread->state & PERL_ITHR_FINISHED) &&
221 (thread->state & PERL_ITHR_UNCALLABLE))
223 (thread->state & PERL_ITHR_NONVIABLE));
225 #ifdef THREAD_SIGNAL_BLOCKING
226 /* We temporarily set the interpreter context to the interpreter being
227 * destroyed. It's in no condition to handle signals while it's being
230 S_block_most_signals(&origmask);
233 interp = thread->interp;
237 PERL_SET_CONTEXT(interp);
238 S_ithread_set(aTHX_ thread);
240 SvREFCNT_dec(thread->params);
241 thread->params = NULL;
244 SvREFCNT_dec(thread->err);
245 thread->err = Nullsv;
248 perl_destruct(interp);
250 thread->interp = NULL;
253 PERL_SET_CONTEXT(aTHX);
254 #ifdef THREAD_SIGNAL_BLOCKING
255 S_set_sigmask(&origmask);
260 /* Decrement the refcount of an ithread, and if it reaches zero, free it.
261 * Must be called with the mutex held.
262 * On return, mutex is released (or destroyed).
265 S_ithread_free(pTHX_ ithread *thread)
266 PERL_TSA_RELEASE(thread->mutex)
273 if (! (thread->state & PERL_ITHR_NONVIABLE)) {
274 assert(thread->count > 0);
275 if (--thread->count > 0) {
276 MUTEX_UNLOCK(&thread->mutex);
279 assert((thread->state & PERL_ITHR_FINISHED) &&
280 (thread->state & PERL_ITHR_UNCALLABLE));
282 MUTEX_UNLOCK(&thread->mutex);
284 /* Main thread (0) is immortal and should never get here */
285 assert(thread->tid != 0);
287 /* Remove from circular list of threads */
288 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
289 assert(thread->prev && thread->next);
290 thread->next->prev = thread->prev;
291 thread->prev->next = thread->next;
294 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
296 /* Thread is now disowned */
297 MUTEX_LOCK(&thread->mutex);
298 S_ithread_clear(aTHX_ thread);
301 handle = thread->handle;
302 thread->handle = NULL;
304 MUTEX_UNLOCK(&thread->mutex);
305 MUTEX_DESTROY(&thread->mutex);
313 PerlMemShared_free(thread);
315 /* total_threads >= 1 is used to veto cleanup by the main thread,
316 * should it happen to exit while other threads still exist.
317 * Decrement this as the very last thing in the thread's existence.
318 * Otherwise, MY_POOL and global state such as PL_op_mutex may get
319 * freed while we're still using it.
321 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
322 MY_POOL.total_threads--;
323 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
328 S_ithread_count_inc(pTHX_ ithread *thread)
329 PERL_TSA_EXCLUDES(thread->mutex)
331 MUTEX_LOCK(&thread->mutex);
333 MUTEX_UNLOCK(&thread->mutex);
337 /* Warn if exiting with any unjoined threads */
341 int veto_cleanup, warn;
344 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
345 veto_cleanup = (MY_POOL.total_threads > 0);
346 warn = (MY_POOL.running_threads || MY_POOL.joinable_threads);
347 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
350 if (ckWARN_d(WARN_THREADS)) {
351 Perl_warn(aTHX_ "Perl exited with active threads:\n\t%"
352 IVdf " running and unjoined\n\t%"
353 IVdf " finished and unjoined\n\t%"
354 IVdf " running and detached\n",
355 MY_POOL.running_threads,
356 MY_POOL.joinable_threads,
357 MY_POOL.detached_threads);
361 return (veto_cleanup);
365 /* Called from perl_destruct() in each thread. If it's the main thread,
366 * stop it from freeing everything if there are other threads still running.
369 Perl_ithread_hook(pTHX)
372 return ((aTHX == MY_POOL.main_thread.interp) ? S_exit_warning(aTHX) : 0);
376 /* MAGIC (in mg.h sense) hooks */
379 ithread_mg_get(pTHX_ SV *sv, MAGIC *mg)
381 ithread *thread = (ithread *)mg->mg_ptr;
382 SvIV_set(sv, PTR2IV(thread));
388 ithread_mg_free(pTHX_ SV *sv, MAGIC *mg)
390 ithread *thread = (ithread *)mg->mg_ptr;
392 MUTEX_LOCK(&thread->mutex);
393 S_ithread_free(aTHX_ thread); /* Releases MUTEX */
398 ithread_mg_dup(pTHX_ MAGIC *mg, CLONE_PARAMS *param)
400 PERL_UNUSED_ARG(param);
401 S_ithread_count_inc(aTHX_ (ithread *)mg->mg_ptr);
405 STATIC const MGVTBL ithread_vtbl = {
406 ithread_mg_get, /* get */
410 ithread_mg_free, /* free */
412 ithread_mg_dup, /* dup */
413 #if (PERL_VERSION > 8) || (PERL_VERSION == 8 && PERL_SUBVERSION > 8)
419 /* Provided default, minimum and rational stack sizes */
421 S_good_stack_size(pTHX_ IV stack_size)
425 /* Use default stack size if no stack size specified */
427 return (MY_POOL.default_stack_size);
430 #ifdef PTHREAD_STACK_MIN
431 /* Can't use less than minimum */
432 if (stack_size < PTHREAD_STACK_MIN) {
433 if (ckWARN(WARN_THREADS)) {
434 Perl_warn(aTHX_ "Using minimum thread stack size of %" IVdf, (IV)PTHREAD_STACK_MIN);
436 return (PTHREAD_STACK_MIN);
440 /* Round up to page size boundary */
441 if (MY_POOL.page_size <= 0) {
442 #if defined(HAS_SYSCONF) && (defined(_SC_PAGESIZE) || defined(_SC_MMAP_PAGE_SIZE))
443 SETERRNO(0, SS_NORMAL);
445 MY_POOL.page_size = sysconf(_SC_PAGESIZE);
447 MY_POOL.page_size = sysconf(_SC_MMAP_PAGE_SIZE);
449 if ((long)MY_POOL.page_size < 0) {
451 SV * const error = get_sv("@", 0);
452 (void)SvUPGRADE(error, SVt_PV);
453 Perl_croak(aTHX_ "PANIC: sysconf: %s", SvPV_nolen(error));
455 Perl_croak(aTHX_ "PANIC: sysconf: pagesize unknown");
459 # ifdef HAS_GETPAGESIZE
460 MY_POOL.page_size = getpagesize();
462 # if defined(I_SYS_PARAM) && defined(PAGESIZE)
463 MY_POOL.page_size = PAGESIZE;
465 MY_POOL.page_size = 8192; /* A conservative default */
468 if (MY_POOL.page_size <= 0) {
469 Perl_croak(aTHX_ "PANIC: bad pagesize %" IVdf, (IV)MY_POOL.page_size);
473 stack_size = ((stack_size + (MY_POOL.page_size - 1)) / MY_POOL.page_size) * MY_POOL.page_size;
479 /* Run code within a JMPENV environment.
480 * Using a separate function avoids
481 * "variable 'foo' might be clobbered by 'longjmp'"
483 * The three _p vars return values to the caller
486 S_jmpenv_run(pTHX_ int action, ithread *thread,
487 int *len_p, int *exit_app_p, int *exit_code_p)
490 volatile I32 oldscope = PL_scopestack_ix;
496 /* Run the specified function */
497 *len_p = (int)call_sv(thread->init_function, thread->gimme|G_EVAL);
498 } else if (action == 1) {
499 /* Warn that thread died */
500 Perl_warn(aTHX_ "Thread %" UVuf " terminated abnormally: %" SVf, thread->tid, ERRSV);
502 /* Warn if there are unjoined threads */
503 S_exit_warning(aTHX);
505 } else if (jmp_rc == 2) {
508 *exit_code_p = STATUS_CURRENT;
509 while (PL_scopestack_ix > oldscope) {
518 /* Starts executing the thread.
519 * Passed as the C level function to run in the new thread.
522 STATIC THREAD_RET_TYPE
523 S_ithread_run(LPVOID arg)
526 S_ithread_run(void * arg)
529 ithread *thread = (ithread *)arg;
530 int exit_app = 0; /* Thread terminated using 'exit' */
532 int died = 0; /* Thread terminated abnormally */
535 dTHXa(thread->interp);
539 /* The following mutex lock + mutex unlock pair explained.
542 * - calls ithread_create (and S_ithread_create), which:
543 * - creates the new thread
544 * - does MUTEX_LOCK(&thread->mutex)
545 * - calls pthread_create(..., S_ithread_run,...)
547 * - starts the S_ithread_run (where we are now), which:
548 * - tries to MUTEX_LOCK(&thread->mutex)
551 * - continues doing more createy stuff
552 * - does MUTEX_UNLOCK(&thread->mutex)
555 * - finishes MUTEX_LOCK(&thread->mutex)
556 * - does MUTEX_UNLOCK(&thread->mutex)
559 MUTEX_LOCK(&thread->mutex);
560 MUTEX_UNLOCK(&thread->mutex);
562 PERL_SET_CONTEXT(thread->interp);
563 S_ithread_set(aTHX_ thread);
565 #ifdef THREAD_SIGNAL_BLOCKING
566 /* Thread starts with most signals blocked - restore the signal mask from
567 * the ithread struct.
569 S_set_sigmask(&thread->initial_sigmask);
572 PL_perl_destruct_level = 2;
575 AV *params = thread->params;
576 int len = (int)av_len(params)+1;
584 /* Put args on the stack */
586 for (ii=0; ii < len; ii++) {
587 XPUSHs(av_shift(params));
591 jmp_rc = S_jmpenv_run(aTHX_ 0, thread, &len, &exit_app, &exit_code);
593 #ifdef THREAD_SIGNAL_BLOCKING
594 /* The interpreter is finished, so this thread can stop receiving
595 * signals. This way, our signal handler doesn't get called in the
596 * middle of our parent thread calling perl_destruct()...
598 S_block_most_signals(NULL);
601 /* Remove args from stack and put back in params array */
603 for (ii=len-1; ii >= 0; ii--) {
605 if (jmp_rc == 0 && (thread->gimme & G_WANT) != G_VOID) {
606 av_store(params, ii, SvREFCNT_inc(sv));
613 /* Check for abnormal termination */
615 died = PERL_ITHR_DIED;
616 thread->err = newSVsv(ERRSV);
617 /* If ERRSV is an object, remember the classname and then
618 * rebless into 'main' so it will survive 'cloning'
620 if (sv_isobject(thread->err)) {
621 thread->err_class = HvNAME(SvSTASH(SvRV(thread->err)));
622 sv_bless(thread->err, gv_stashpv("main", 0));
625 if (ckWARN_d(WARN_THREADS)) {
626 (void)S_jmpenv_run(aTHX_ 1, thread, NULL,
627 &exit_app, &exit_code);
631 /* Release function ref */
632 SvREFCNT_dec(thread->init_function);
633 thread->init_function = Nullsv;
636 PerlIO_flush((PerlIO *)NULL);
638 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
639 MUTEX_LOCK(&thread->mutex);
640 /* Mark as finished */
641 thread->state |= (PERL_ITHR_FINISHED | died);
642 /* Clear exit flag if required */
643 if (thread->state & PERL_ITHR_THREAD_EXIT_ONLY) {
647 /* Adjust thread status counts */
648 if (thread->state & PERL_ITHR_DETACHED) {
649 MY_POOL.detached_threads--;
651 MY_POOL.running_threads--;
652 MY_POOL.joinable_threads++;
654 MUTEX_UNLOCK(&thread->mutex);
655 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
657 /* Exit application if required */
659 (void)S_jmpenv_run(aTHX_ 2, thread, NULL, &exit_app, &exit_code);
663 /* At this point, the interpreter may have been freed, so call
664 * free in the the context of of the 'main' interpreter which
665 * can't have been freed due to the veto_cleanup mechanism.
667 aTHX = MY_POOL.main_thread.interp;
669 MUTEX_LOCK(&thread->mutex);
670 S_ithread_free(aTHX_ thread); /* Releases MUTEX */
680 /* Type conversion helper functions */
683 S_ithread_to_SV(pTHX_ SV *obj, ithread *thread, char *classname, bool inc)
689 S_ithread_count_inc(aTHX_ thread);
695 sv = newSVrv(obj, classname);
696 sv_setiv(sv, PTR2IV(thread));
697 mg = sv_magicext(sv, Nullsv, PERL_MAGIC_shared_scalar, &ithread_vtbl, (char *)thread, 0);
698 mg->mg_flags |= MGf_DUP;
705 S_SV_to_ithread(pTHX_ SV *sv)
707 /* Argument is a thread */
709 return (INT2PTR(ithread *, SvIV(SvRV(sv))));
711 /* Argument is classname, therefore return current thread */
712 return (S_ithread_get(aTHX));
717 * Called in context of parent thread.
718 * Called with my_pool->create_destruct_mutex locked.
719 * (Unlocked both on error and on success.)
723 PerlInterpreter *parent_perl,
731 PERL_TSA_RELEASE(my_pool->create_destruct_mutex)
735 ithread *current_thread = S_ithread_get(aTHX);
739 #if PERL_VERSION <= 8 && PERL_SUBVERSION <= 7
740 SV **tmps_tmp = PL_tmps_stack;
741 IV tmps_ix = PL_tmps_ix;
744 int rc_stack_size = 0;
745 int rc_thread_create = 0;
748 /* Allocate thread structure in context of the main thread's interpreter */
750 PERL_SET_CONTEXT(my_pool->main_thread.interp);
751 thread = (ithread *)PerlMemShared_malloc(sizeof(ithread));
753 PERL_SET_CONTEXT(aTHX);
755 /* This lock was acquired in ithread_create()
756 * prior to calling S_ithread_create(). */
757 MUTEX_UNLOCK(&my_pool->create_destruct_mutex);
759 int fd = PerlIO_fileno(Perl_error_log);
761 /* If there's no error_log, we cannot scream about it missing. */
762 PERL_UNUSED_RESULT(PerlLIO_write(fd, PL_no_mem, strlen(PL_no_mem)));
767 Zero(thread, 1, ithread);
769 /* Add to threads list */
770 thread->next = &my_pool->main_thread;
771 thread->prev = my_pool->main_thread.prev;
772 my_pool->main_thread.prev = thread;
773 thread->prev->next = thread;
774 my_pool->total_threads++;
776 /* 1 ref to be held by the local var 'thread' in S_ithread_run().
777 * 1 ref to be held by the threads object that we assume we will
778 * be embedded in upon our return.
779 * 1 ref to be the responsibility of join/detach, so we don't get
780 * freed until join/detach, even if no thread objects remain.
781 * This allows the following to work:
782 * { threads->create(sub{...}); } threads->object(1)->join;
786 /* Block new thread until ->create() call finishes */
787 MUTEX_INIT(&thread->mutex);
788 MUTEX_LOCK(&thread->mutex); /* See S_ithread_run() for more detail. */
790 thread->tid = my_pool->tid_counter++;
791 thread->stack_size = S_good_stack_size(aTHX_ stack_size);
792 thread->gimme = gimme;
793 thread->state = exit_opt;
795 /* "Clone" our interpreter into the thread's interpreter.
796 * This gives thread access to "static data" and code.
798 PerlIO_flush((PerlIO *)NULL);
799 S_ithread_set(aTHX_ thread);
801 SAVEBOOL(PL_srand_called); /* Save this so it becomes the correct value */
802 PL_srand_called = FALSE; /* Set it to false so we can detect if it gets
803 set during the clone */
805 #ifdef THREAD_SIGNAL_BLOCKING
806 /* perl_clone() will leave us the new interpreter's context. This poses
807 * two problems for our signal handler. First, it sets the new context
808 * before the new interpreter struct is fully initialized, so our signal
809 * handler might find bogus data in the interpreter struct it gets.
810 * Second, even if the interpreter is initialized before a signal comes in,
811 * we would like to avoid that interpreter receiving notifications for
812 * signals (especially when they ought to be for the one running in this
813 * thread), until it is running in its own thread. Another problem is that
814 * the new thread will not have set the context until some time after it
815 * has started, so it won't be safe for our signal handler to run until
818 * So we block most signals here, so the new thread will inherit the signal
819 * mask, and unblock them right after the thread creation. The original
820 * mask is saved in the thread struct so that the new thread can restore
823 S_block_most_signals(&thread->initial_sigmask);
827 thread->interp = perl_clone(aTHX, CLONEf_KEEP_PTR_TABLE | CLONEf_CLONE_HOST);
829 thread->interp = perl_clone(aTHX, CLONEf_KEEP_PTR_TABLE);
832 /* perl_clone() leaves us in new interpreter's context. As it is tricky
833 * to spot an implicit aTHX, create a new scope with aTHX matching the
834 * context for the duration of our work for new interpreter.
837 #if (PERL_VERSION > 13) || (PERL_VERSION == 13 && PERL_SUBVERSION > 1)
838 CLONE_PARAMS *clone_param = Perl_clone_params_new(aTHX, thread->interp);
840 CLONE_PARAMS clone_param_s;
841 CLONE_PARAMS *clone_param = &clone_param_s;
843 dTHXa(thread->interp);
847 #if (PERL_VERSION < 13) || (PERL_VERSION == 13 && PERL_SUBVERSION <= 1)
848 clone_param->flags = 0;
851 /* Here we remove END blocks since they should only run in the thread
854 SvREFCNT_dec(PL_endav);
857 if (SvPOK(init_function)) {
858 thread->init_function = newSV(0);
859 sv_copypv(thread->init_function, init_function);
861 thread->init_function = sv_dup_inc(init_function, clone_param);
864 thread->params = params = newAV();
865 av_extend(params, num_params - 1);
866 AvFILLp(params) = num_params - 1;
867 array = AvARRAY(params);
869 /* params_start is an offset onto the Perl stack. This can be
870 reallocated (and hence move) as a side effect of calls to
871 perl_clone() and sv_dup_inc(). Hence copy the parameters
872 somewhere under our control first, before duplicating. */
873 #if (PERL_VERSION > 8)
874 Copy(parent_perl->Istack_base + params_start, array, num_params, SV *);
876 Copy(parent_perl->Tstack_base + params_start, array, num_params, SV *);
878 while (num_params--) {
879 *array = sv_dup_inc(*array, clone_param);
882 #if (PERL_VERSION > 13) || (PERL_VERSION == 13 && PERL_SUBVERSION > 1)
883 Perl_clone_params_del(clone_param);
886 #if PERL_VERSION <= 8 && PERL_SUBVERSION <= 7
887 /* The code below checks that anything living on the tmps stack and
888 * has been cloned (so it lives in the ptr_table) has a refcount
891 * If the refcount is 0 it means that a something on the stack/context
892 * was holding a reference to it and since we init_stacks() in
893 * perl_clone that won't get cleaned and we will get a leaked scalar.
894 * The reason it was cloned was that it lived on the @_ stack.
896 * Example of this can be found in bugreport 15837 where calls in the
897 * parameter list end up as a temp.
899 * As of 5.8.8 this is done in perl_clone.
901 while (tmps_ix > 0) {
902 SV* sv = (SV*)ptr_table_fetch(PL_ptr_table, tmps_tmp[tmps_ix]);
904 if (sv && SvREFCNT(sv) == 0) {
905 SvREFCNT_inc_void(sv);
911 SvTEMP_off(thread->init_function);
912 ptr_table_free(PL_ptr_table);
914 PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
916 S_ithread_set(aTHX_ current_thread);
917 PERL_SET_CONTEXT(aTHX);
919 /* Create/start the thread */
921 thread->handle = CreateThread(NULL,
922 (DWORD)thread->stack_size,
925 STACK_SIZE_PARAM_IS_A_RESERVATION,
929 STATIC pthread_attr_t attr;
930 STATIC int attr_inited = 0;
931 STATIC int attr_joinable = PTHREAD_CREATE_JOINABLE;
933 pthread_attr_init(&attr);
937 # ifdef PTHREAD_ATTR_SETDETACHSTATE
938 /* Threads start out joinable */
939 PTHREAD_ATTR_SETDETACHSTATE(&attr, attr_joinable);
942 # ifdef _POSIX_THREAD_ATTR_STACKSIZE
943 /* Set thread's stack size */
944 if (thread->stack_size > 0) {
945 rc_stack_size = pthread_attr_setstacksize(&attr, (size_t)thread->stack_size);
949 /* Create the thread */
950 if (! rc_stack_size) {
951 # ifdef OLD_PTHREADS_API
952 rc_thread_create = pthread_create(&thread->thr,
957 # if defined(HAS_PTHREAD_ATTR_SETSCOPE) && defined(PTHREAD_SCOPE_SYSTEM)
958 pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);
960 rc_thread_create = pthread_create(&thread->thr,
967 #ifdef THREAD_SIGNAL_BLOCKING
968 /* Now it's safe to accept signals, since we're in our own interpreter's
969 * context and we have created the thread.
971 S_set_sigmask(&thread->initial_sigmask);
974 # ifdef _POSIX_THREAD_ATTR_STACKSIZE
975 /* Try to get thread's actual stack size */
979 stacksize = pthread_attr_getstacksize(attr);
981 if (! pthread_attr_getstacksize(&attr, &stacksize))
984 thread->stack_size = (IV)stacksize;
991 /* Check for errors */
993 if (thread->handle == NULL) {
995 if (rc_stack_size || rc_thread_create) {
997 /* Must unlock mutex for destruct call */
998 /* This lock was acquired in ithread_create()
999 * prior to calling S_ithread_create(). */
1000 MUTEX_UNLOCK(&my_pool->create_destruct_mutex);
1001 thread->state |= PERL_ITHR_NONVIABLE;
1002 S_ithread_free(aTHX_ thread); /* Releases MUTEX */
1004 if (ckWARN_d(WARN_THREADS)) {
1005 if (rc_stack_size) {
1006 Perl_warn(aTHX_ "Thread creation failed: pthread_attr_setstacksize(%" IVdf ") returned %d", thread->stack_size, rc_stack_size);
1008 Perl_warn(aTHX_ "Thread creation failed: pthread_create returned %d", rc_thread_create);
1015 my_pool->running_threads++;
1016 MUTEX_UNLOCK(&my_pool->create_destruct_mutex);
1019 CLANG_DIAG_IGNORE(-Wthread-safety);
1020 /* warning: mutex 'thread->mutex' is not held on every path through here [-Wthread-safety-analysis] */
1022 #if defined(__clang__) || defined(__clang)
1026 #endif /* USE_ITHREADS */
1029 MODULE = threads PACKAGE = threads PREFIX = ithread_
1039 SV *function_to_call;
1044 SV *thread_exit_only;
1049 if ((items >= 2) && SvROK(ST(1)) && SvTYPE(SvRV(ST(1)))==SVt_PVHV) {
1051 Perl_croak(aTHX_ "Usage: threads->create(\\%%specs, function, ...)");
1053 specs = (HV*)SvRV(ST(1));
1057 Perl_croak(aTHX_ "Usage: threads->create(function, ...)");
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);
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;
1080 function_to_call = ST(idx+1);
1086 if ((svp = hv_fetchs(specs, "stack", 0))) {
1087 stack_size = SvIV(*svp);
1088 } else if ((svp = hv_fetchs(specs, "stacksize", 0))) {
1089 stack_size = SvIV(*svp);
1090 } else if ((svp = hv_fetchs(specs, "stack_size", 0))) {
1091 stack_size = SvIV(*svp);
1095 if ((svp = hv_fetchs(specs, "context", 0))) {
1096 str = (char *)SvPV_nolen(*svp);
1113 Perl_croak(aTHX_ "Invalid context: %s", str);
1115 } else if ((svp = hv_fetchs(specs, "array", 0))) {
1119 } else if ((svp = hv_fetchs(specs, "list", 0))) {
1123 } else if ((svp = hv_fetchs(specs, "scalar", 0))) {
1127 } else if ((svp = hv_fetchs(specs, "void", 0))) {
1133 /* exit => thread_only */
1134 if ((svp = hv_fetchs(specs, "exit", 0))) {
1135 str = (char *)SvPV_nolen(*svp);
1136 exit_opt = (*str == 't' || *str == 'T')
1137 ? PERL_ITHR_THREAD_EXIT_ONLY : 0;
1140 if (context == -1) {
1141 context = GIMME_V; /* Implicit context */
1143 context |= (GIMME_V & (~(G_ARRAY|G_SCALAR|G_VOID)));
1147 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
1148 thread = S_ithread_create(aTHX_ &MY_POOL,
1154 items > 2 ? items - 2 : 0);
1156 XSRETURN_UNDEF; /* Mutex already unlocked */
1158 ST(0) = sv_2mortal(S_ithread_to_SV(aTHX_ Nullsv, thread, classname, FALSE));
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);
1167 /* XSRETURN(1); - implied */
1177 int want_running = 0;
1181 /* Class method only */
1183 Perl_croak(aTHX_ "Usage: threads->list(...)");
1185 classname = (char *)SvPV_nolen(ST(0));
1187 /* Calling context */
1188 list_context = (GIMME_V == G_ARRAY);
1190 /* Running or joinable parameter */
1192 want_running = SvTRUE(ST(1));
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)
1201 MUTEX_LOCK(&thread->mutex);
1202 state = thread->state;
1203 MUTEX_UNLOCK(&thread->mutex);
1205 /* Ignore detached or joined threads */
1206 if (state & PERL_ITHR_UNCALLABLE) {
1210 /* Filter per parameter */
1213 if (state & PERL_ITHR_FINISHED) {
1214 continue; /* Not running */
1217 if (! (state & PERL_ITHR_FINISHED)) {
1218 continue; /* Still running - not joinable yet */
1223 /* Push object on stack if list context */
1225 XPUSHs(sv_2mortal(S_ithread_to_SV(aTHX_ Nullsv, thread, classname, TRUE)));
1229 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
1230 /* If scalar context, send back count */
1231 if (! list_context) {
1242 /* Class method only */
1243 if ((items != 1) || SvROK(ST(0))) {
1244 Perl_croak(aTHX_ "Usage: threads->self()");
1246 classname = (char *)SvPV_nolen(ST(0));
1248 thread = S_ithread_get(aTHX);
1250 ST(0) = sv_2mortal(S_ithread_to_SV(aTHX_ Nullsv, thread, classname, TRUE));
1251 /* XSRETURN(1); - implied */
1259 PERL_UNUSED_VAR(items);
1260 thread = S_SV_to_ithread(aTHX_ ST(0));
1261 XST_mUV(0, thread->tid);
1262 /* XSRETURN(1); - implied */
1269 ithread *current_thread;
1280 /* Object method only */
1281 if ((items != 1) || ! sv_isobject(ST(0))) {
1282 Perl_croak(aTHX_ "Usage: $thr->join()");
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);
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");
1300 /* Mark as joined */
1301 thread->state |= PERL_ITHR_JOINED;
1302 MUTEX_UNLOCK(&thread->mutex);
1304 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
1305 MY_POOL.joinable_threads--;
1306 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
1308 /* Join the thread */
1310 if (WaitForSingleObject(thread->handle, INFINITE) != WAIT_OBJECT_0) {
1311 /* Timeout/abandonment unexpected here; check $^E */
1312 Perl_croak(aTHX_ "PANIC: underlying join failed");
1315 if ((rc_join = pthread_join(thread->thr, &retval)) != 0) {
1316 /* In progress/deadlock/unknown unexpected here; check $! */
1318 Perl_croak(aTHX_ "PANIC: underlying join failed");
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)
1328 PerlInterpreter *other_perl;
1329 CLONE_PARAMS clone_params;
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;
1349 PerlInterpreter *other_perl = thread->interp;
1350 CLONE_PARAMS *clone_params = Perl_clone_params_new(other_perl, aTHX);
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;
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);
1373 S_ithread_free(aTHX_ thread); /* Releases MUTEX */
1375 /* If no return values, then just return */
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));
1387 /* Free return value array */
1388 SvREFCNT_dec(params);
1394 PERL_UNUSED_VAR(items);
1405 PERL_UNUSED_VAR(items);
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;
1415 /* Windows has no 'detach thread' function */
1417 PERL_THREAD_DETACH(thread->thr);
1419 if (thread->state & PERL_ITHR_FINISHED) {
1420 MY_POOL.joinable_threads--;
1422 MY_POOL.running_threads--;
1423 MY_POOL.detached_threads++;
1426 MUTEX_UNLOCK(&thread->mutex);
1427 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
1430 Perl_croak(aTHX_ (detach_err & PERL_ITHR_DETACHED)
1431 ? "Thread already detached"
1432 : "Cannot detach a joined thread");
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))
1441 S_ithread_clear(aTHX_ thread);
1443 S_ithread_free(aTHX_ thread); /* Releases MUTEX */
1454 /* Must have safe signals */
1455 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG) {
1456 Perl_croak(aTHX_ "Cannot signal threads without safe signals");
1459 /* Object method only */
1460 if ((items != 2) || ! sv_isobject(ST(0))) {
1461 Perl_croak(aTHX_ "Usage: $thr->kill('SIG...')");
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') {
1470 if ((signal = whichsig(sig_name)) < 0) {
1471 Perl_croak(aTHX_ "Unrecognized signal name: %s", sig_name);
1474 signal = SvIV(ST(1));
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]++;
1488 /* Ignore signal to terminated/finished thread */
1491 MUTEX_UNLOCK(&thread->mutex);
1494 Perl_croak(aTHX_ "Signal %s received in thread %" UVuf
1495 ", but no signal handler set.",
1496 sig_name, thread->tid);
1499 /* Return the thread to allow for method chaining */
1501 /* XSRETURN(1); - implied */
1505 ithread_DESTROY(...)
1507 PERL_UNUSED_VAR(items);
1508 sv_unmagic(SvRV(ST(0)), PERL_MAGIC_shared_scalar);
1516 PERL_UNUSED_VAR(items);
1518 /* Compares TIDs to determine thread equality */
1519 if (sv_isobject(ST(0)) && sv_isobject(ST(1))) {
1520 ithread *thr1 = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1521 ithread *thr2 = INT2PTR(ithread *, SvIV(SvRV(ST(1))));
1522 are_equal = (thr1->tid == thr2->tid);
1527 /* Return 0 on false for backward compatibility */
1530 /* XSRETURN(1); - implied */
1544 /* Class method only */
1546 Perl_croak(aTHX_ "Usage: threads->object($tid)");
1548 classname = (char *)SvPV_nolen(ST(0));
1550 /* Turn $tid from PVLV to SV if needed (bug #73330) */
1554 if ((items < 2) || ! SvOK(arg)) {
1558 /* threads->object($tid) */
1561 /* If current thread wants its own object, then behave the same as
1563 thread = S_ithread_get(aTHX);
1564 if (thread->tid == tid) {
1565 ST(0) = sv_2mortal(S_ithread_to_SV(aTHX_ Nullsv, thread, classname, TRUE));
1569 /* Walk through threads list */
1570 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
1571 for (thread = MY_POOL.main_thread.next;
1572 thread != &MY_POOL.main_thread;
1573 thread = thread->next)
1576 if (thread->tid == tid) {
1577 /* Ignore if detached or joined */
1578 MUTEX_LOCK(&thread->mutex);
1579 state = thread->state;
1580 MUTEX_UNLOCK(&thread->mutex);
1581 if (! (state & PERL_ITHR_UNCALLABLE)) {
1582 /* Put object on stack */
1583 ST(0) = sv_2mortal(S_ithread_to_SV(aTHX_ Nullsv, thread, classname, TRUE));
1589 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
1595 /* XSRETURN(1); - implied */
1599 ithread__handle(...);
1603 PERL_UNUSED_VAR(items);
1604 thread = S_SV_to_ithread(aTHX_ ST(0));
1606 XST_mUV(0, PTR2UV(&thread->handle));
1608 XST_mUV(0, PTR2UV(&thread->thr));
1610 /* XSRETURN(1); - implied */
1614 ithread_get_stack_size(...)
1619 PERL_UNUSED_VAR(items);
1620 if (sv_isobject(ST(0))) {
1621 /* $thr->get_stack_size() */
1622 ithread *thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1623 stack_size = thread->stack_size;
1625 /* threads->get_stack_size() */
1626 stack_size = MY_POOL.default_stack_size;
1628 XST_mIV(0, stack_size);
1629 /* XSRETURN(1); - implied */
1633 ithread_set_stack_size(...)
1639 Perl_croak(aTHX_ "Usage: threads->set_stack_size($size)");
1641 if (sv_isobject(ST(0))) {
1642 Perl_croak(aTHX_ "Cannot change stack size of an existing thread");
1644 if (! looks_like_number(ST(1))) {
1645 Perl_croak(aTHX_ "Stack size must be numeric");
1648 old_size = MY_POOL.default_stack_size;
1649 MY_POOL.default_stack_size = S_good_stack_size(aTHX_ SvIV(ST(1)));
1650 XST_mIV(0, old_size);
1651 /* XSRETURN(1); - implied */
1655 ithread_is_running(...)
1659 /* Object method only */
1660 if ((items != 1) || ! sv_isobject(ST(0))) {
1661 Perl_croak(aTHX_ "Usage: $thr->is_running()");
1664 thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1665 MUTEX_LOCK(&thread->mutex);
1666 ST(0) = (thread->state & PERL_ITHR_FINISHED) ? &PL_sv_no : &PL_sv_yes;
1667 MUTEX_UNLOCK(&thread->mutex);
1668 /* XSRETURN(1); - implied */
1672 ithread_is_detached(...)
1676 PERL_UNUSED_VAR(items);
1677 thread = S_SV_to_ithread(aTHX_ ST(0));
1678 MUTEX_LOCK(&thread->mutex);
1679 ST(0) = (thread->state & PERL_ITHR_DETACHED) ? &PL_sv_yes : &PL_sv_no;
1680 MUTEX_UNLOCK(&thread->mutex);
1681 /* XSRETURN(1); - implied */
1685 ithread_is_joinable(...)
1689 /* Object method only */
1690 if ((items != 1) || ! sv_isobject(ST(0))) {
1691 Perl_croak(aTHX_ "Usage: $thr->is_joinable()");
1694 thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1695 MUTEX_LOCK(&thread->mutex);
1696 ST(0) = ((thread->state & PERL_ITHR_FINISHED) &&
1697 ! (thread->state & PERL_ITHR_UNCALLABLE))
1698 ? &PL_sv_yes : &PL_sv_no;
1699 MUTEX_UNLOCK(&thread->mutex);
1700 /* XSRETURN(1); - implied */
1704 ithread_wantarray(...)
1708 PERL_UNUSED_VAR(items);
1709 thread = S_SV_to_ithread(aTHX_ ST(0));
1710 ST(0) = ((thread->gimme & G_WANT) == G_ARRAY) ? &PL_sv_yes :
1711 ((thread->gimme & G_WANT) == G_VOID) ? &PL_sv_undef
1712 /* G_SCALAR */ : &PL_sv_no;
1713 /* XSRETURN(1); - implied */
1717 ithread_set_thread_exit_only(...)
1722 Perl_croak(aTHX_ "Usage: ->set_thread_exit_only(boolean)");
1724 thread = S_SV_to_ithread(aTHX_ ST(0));
1725 MUTEX_LOCK(&thread->mutex);
1726 if (SvTRUE(ST(1))) {
1727 thread->state |= PERL_ITHR_THREAD_EXIT_ONLY;
1729 thread->state &= ~PERL_ITHR_THREAD_EXIT_ONLY;
1731 MUTEX_UNLOCK(&thread->mutex);
1740 /* Object method only */
1741 if ((items != 1) || ! sv_isobject(ST(0))) {
1742 Perl_croak(aTHX_ "Usage: $thr->err()");
1745 thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1746 MUTEX_LOCK(&thread->mutex);
1748 /* If thread died, then clone the error into the calling thread */
1749 if (thread->state & PERL_ITHR_DIED) {
1750 #if (PERL_VERSION < 13) || (PERL_VERSION == 13 && PERL_SUBVERSION <= 1)
1751 PerlInterpreter *other_perl;
1752 CLONE_PARAMS clone_params;
1753 ithread *current_thread;
1755 other_perl = thread->interp;
1756 clone_params.stashes = newAV();
1757 clone_params.flags = CLONEf_JOIN_IN;
1758 PL_ptr_table = ptr_table_new();
1759 current_thread = S_ithread_get(aTHX);
1760 S_ithread_set(aTHX_ thread);
1761 /* Ensure 'meaningful' addresses retain their meaning */
1762 ptr_table_store(PL_ptr_table, &other_perl->Isv_undef, &PL_sv_undef);
1763 ptr_table_store(PL_ptr_table, &other_perl->Isv_no, &PL_sv_no);
1764 ptr_table_store(PL_ptr_table, &other_perl->Isv_yes, &PL_sv_yes);
1765 err = sv_dup(thread->err, &clone_params);
1766 S_ithread_set(aTHX_ current_thread);
1767 SvREFCNT_dec(clone_params.stashes);
1768 SvREFCNT_inc_void(err);
1769 /* If error was an object, bless it into the correct class */
1770 if (thread->err_class) {
1771 sv_bless(err, gv_stashpv(thread->err_class, 1));
1773 ptr_table_free(PL_ptr_table);
1774 PL_ptr_table = NULL;
1776 PerlInterpreter *other_perl = thread->interp;
1777 CLONE_PARAMS *clone_params = Perl_clone_params_new(other_perl, aTHX);
1778 ithread *current_thread;
1780 clone_params->flags |= CLONEf_JOIN_IN;
1781 PL_ptr_table = ptr_table_new();
1782 current_thread = S_ithread_get(aTHX);
1783 S_ithread_set(aTHX_ thread);
1784 /* Ensure 'meaningful' addresses retain their meaning */
1785 ptr_table_store(PL_ptr_table, &other_perl->Isv_undef, &PL_sv_undef);
1786 ptr_table_store(PL_ptr_table, &other_perl->Isv_no, &PL_sv_no);
1787 ptr_table_store(PL_ptr_table, &other_perl->Isv_yes, &PL_sv_yes);
1788 err = sv_dup(thread->err, clone_params);
1789 S_ithread_set(aTHX_ current_thread);
1790 Perl_clone_params_del(clone_params);
1791 SvREFCNT_inc_void(err);
1792 /* If error was an object, bless it into the correct class */
1793 if (thread->err_class) {
1794 sv_bless(err, gv_stashpv(thread->err_class, 1));
1796 ptr_table_free(PL_ptr_table);
1797 PL_ptr_table = NULL;
1801 MUTEX_UNLOCK(&thread->mutex);
1807 ST(0) = sv_2mortal(err);
1808 /* XSRETURN(1); - implied */
1811 #endif /* USE_ITHREADS */
1817 SV *my_pool_sv = *hv_fetch(PL_modglobal, MY_POOL_KEY,
1818 sizeof(MY_POOL_KEY)-1, TRUE);
1819 my_pool_t *my_poolp = (my_pool_t*)SvPVX(newSV(sizeof(my_pool_t)-1));
1823 Zero(my_poolp, 1, my_pool_t);
1824 sv_setuv(my_pool_sv, PTR2UV(my_poolp));
1826 PL_perl_destruct_level = 2;
1827 MUTEX_INIT(&MY_POOL.create_destruct_mutex);
1828 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
1830 PL_threadhook = &Perl_ithread_hook;
1832 MY_POOL.tid_counter = 1;
1833 # ifdef THREAD_CREATE_NEEDS_STACK
1834 MY_POOL.default_stack_size = THREAD_CREATE_NEEDS_STACK;
1837 /* The 'main' thread is thread 0.
1838 * It is detached (unjoinable) and immortal.
1841 MUTEX_INIT(&MY_POOL.main_thread.mutex);
1843 /* Head of the threads list */
1844 MY_POOL.main_thread.next = &MY_POOL.main_thread;
1845 MY_POOL.main_thread.prev = &MY_POOL.main_thread;
1847 MY_POOL.main_thread.count = 1; /* Immortal */
1849 MY_POOL.main_thread.interp = aTHX;
1850 MY_POOL.main_thread.state = PERL_ITHR_DETACHED; /* Detached */
1851 MY_POOL.main_thread.stack_size = MY_POOL.default_stack_size;
1853 MY_POOL.main_thread.thr = GetCurrentThreadId();
1855 MY_POOL.main_thread.thr = pthread_self();
1858 S_ithread_set(aTHX_ &MY_POOL.main_thread);
1859 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
1860 #endif /* USE_ITHREADS */