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)
19 # define NEED_PL_signals
20 # define NEED_newRV_noinc
21 # define NEED_sv_2pv_flags
30 /* Supposed to be in Winbase.h */
31 # ifndef STACK_SIZE_PARAM_IS_A_RESERVATION
32 # define STACK_SIZE_PARAM_IS_A_RESERVATION 0x00010000
34 # include <win32thread.h>
37 typedef perl_os_thread pthread_t;
42 # define PERL_THREAD_SETSPECIFIC(k,v) pthread_setspecific(k,v)
43 # ifdef OLD_PTHREADS_API
44 # define PERL_THREAD_DETACH(t) pthread_detach(&(t))
46 # define PERL_THREAD_DETACH(t) pthread_detach((t))
49 #if !defined(HAS_GETPAGESIZE) && defined(I_SYS_PARAM)
50 # include <sys/param.h>
53 /* Values for 'state' member */
54 #define PERL_ITHR_DETACHED 1 /* Thread has been detached */
55 #define PERL_ITHR_JOINED 2 /* Thread is being / has been joined */
56 #define PERL_ITHR_FINISHED 4 /* Thread has finished execution */
57 #define PERL_ITHR_THREAD_EXIT_ONLY 8 /* exit() only exits current thread */
58 #define PERL_ITHR_NONVIABLE 16 /* Thread creation failed */
59 #define PERL_ITHR_DIED 32 /* Thread finished by dying */
61 #define PERL_ITHR_UNCALLABLE (PERL_ITHR_DETACHED|PERL_ITHR_JOINED)
64 typedef struct _ithread {
65 struct _ithread *next; /* Next thread in the list */
66 struct _ithread *prev; /* Prev thread in the list */
67 PerlInterpreter *interp; /* The threads interpreter */
68 UV tid; /* Threads module's thread id */
69 perl_mutex mutex; /* Mutex for updating things in this struct */
70 int count; /* Reference count. See S_ithread_create. */
71 int state; /* Detached, joined, finished, etc. */
72 int gimme; /* Context of create */
73 SV *init_function; /* Code to run */
74 AV *params; /* Args to pass function */
76 DWORD thr; /* OS's idea if thread id */
77 HANDLE handle; /* OS's waitable handle */
79 pthread_t thr; /* OS's handle for the thread */
82 SV *err; /* Error from abnormally terminated thread */
83 char *err_class; /* Error object's classname if applicable */
85 sigset_t initial_sigmask; /* Thread wakes up with signals blocked */
90 #define MY_CXT_KEY "threads::_cxt" XS_VERSION
93 /* Used by Perl interpreter for thread context switching */
100 #define MY_POOL_KEY "threads::_pool" XS_VERSION
103 /* Structure for 'main' thread
104 * Also forms the 'base' for the doubly-linked list of threads */
107 /* Protects the creation and destruction of threads*/
108 perl_mutex create_destruct_mutex;
115 IV default_stack_size;
120 SV *my_pool_sv = *hv_fetch(PL_modglobal, MY_POOL_KEY, \
121 sizeof(MY_POOL_KEY)-1, TRUE); \
122 my_pool_t *my_poolp = INT2PTR(my_pool_t*, SvUV(my_pool_sv))
124 #define MY_POOL (*my_poolp)
127 /* Block most signals for calling thread, setting the old signal mask to
128 * oldmask, if it is not NULL */
130 S_block_most_signals(sigset_t *oldmask)
134 sigfillset(&newmask);
135 /* Don't block certain "important" signals (stolen from mg.c) */
137 sigdelset(&newmask, SIGILL);
140 sigdelset(&newmask, SIGBUS);
143 sigdelset(&newmask, SIGSEGV);
147 /* no per-thread blocking available */
148 return sigprocmask(SIG_BLOCK, &newmask, oldmask);
150 return pthread_sigmask(SIG_BLOCK, &newmask, oldmask);
154 /* Set the signal mask for this thread to newmask */
156 S_set_sigmask(sigset_t *newmask)
159 return sigprocmask(SIG_SETMASK, newmask, NULL);
161 return pthread_sigmask(SIG_SETMASK, newmask, NULL);
166 /* Used by Perl interpreter for thread context switching */
168 S_ithread_set(pTHX_ ithread *thread)
171 MY_CXT.context = thread;
178 return (MY_CXT.context);
182 /* Free any data (such as the Perl interpreter) attached to an ithread
183 * structure. This is a bit like undef on SVs, where the SV isn't freed,
184 * but the PVX is. Must be called with thread->mutex already locked. Also,
185 * must be called with MY_POOL.create_destruct_mutex unlocked as destruction
186 * of the interpreter can lead to recursive destruction calls that could
187 * lead to a deadlock on that mutex.
190 S_ithread_clear(pTHX_ ithread *thread)
192 PerlInterpreter *interp;
197 assert(((thread->state & PERL_ITHR_FINISHED) &&
198 (thread->state & PERL_ITHR_UNCALLABLE))
200 (thread->state & PERL_ITHR_NONVIABLE));
203 /* We temporarily set the interpreter context to the interpreter being
204 * destroyed. It's in no condition to handle signals while it's being
207 S_block_most_signals(&origmask);
210 interp = thread->interp;
214 PERL_SET_CONTEXT(interp);
215 S_ithread_set(aTHX_ thread);
217 SvREFCNT_dec(thread->params);
218 thread->params = NULL;
221 SvREFCNT_dec(thread->err);
222 thread->err = Nullsv;
225 perl_destruct(interp);
227 thread->interp = NULL;
230 PERL_SET_CONTEXT(aTHX);
232 S_set_sigmask(&origmask);
237 /* Decrement the refcount of an ithread, and if it reaches zero, free it.
238 * Must be called with the mutex held.
239 * On return, mutex is released (or destroyed).
242 S_ithread_free(pTHX_ ithread *thread)
249 if (! (thread->state & PERL_ITHR_NONVIABLE)) {
250 assert(thread->count > 0);
251 if (--thread->count > 0) {
252 MUTEX_UNLOCK(&thread->mutex);
255 assert((thread->state & PERL_ITHR_FINISHED) &&
256 (thread->state & PERL_ITHR_UNCALLABLE));
258 MUTEX_UNLOCK(&thread->mutex);
260 /* Main thread (0) is immortal and should never get here */
261 assert(thread->tid != 0);
263 /* Remove from circular list of threads */
264 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
265 assert(thread->prev && thread->next);
266 thread->next->prev = thread->prev;
267 thread->prev->next = thread->next;
270 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
272 /* Thread is now disowned */
273 MUTEX_LOCK(&thread->mutex);
274 S_ithread_clear(aTHX_ thread);
277 handle = thread->handle;
278 thread->handle = NULL;
280 MUTEX_UNLOCK(&thread->mutex);
281 MUTEX_DESTROY(&thread->mutex);
289 PerlMemShared_free(thread);
291 /* total_threads >= 1 is used to veto cleanup by the main thread,
292 * should it happen to exit while other threads still exist.
293 * Decrement this as the very last thing in the thread's existence.
294 * Otherwise, MY_POOL and global state such as PL_op_mutex may get
295 * freed while we're still using it.
297 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
298 MY_POOL.total_threads--;
299 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
304 S_ithread_count_inc(pTHX_ ithread *thread)
306 MUTEX_LOCK(&thread->mutex);
308 MUTEX_UNLOCK(&thread->mutex);
312 /* Warn if exiting with any unjoined threads */
316 int veto_cleanup, warn;
319 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
320 veto_cleanup = (MY_POOL.total_threads > 0);
321 warn = (MY_POOL.running_threads || MY_POOL.joinable_threads);
322 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
325 if (ckWARN_d(WARN_THREADS)) {
326 Perl_warn(aTHX_ "Perl exited with active threads:\n\t%"
327 IVdf " running and unjoined\n\t%"
328 IVdf " finished and unjoined\n\t%"
329 IVdf " running and detached\n",
330 MY_POOL.running_threads,
331 MY_POOL.joinable_threads,
332 MY_POOL.detached_threads);
336 return (veto_cleanup);
340 /* Called from perl_destruct() in each thread. If it's the main thread,
341 * stop it from freeing everything if there are other threads still running.
344 Perl_ithread_hook(pTHX)
347 return ((aTHX == MY_POOL.main_thread.interp) ? S_exit_warning(aTHX) : 0);
351 /* MAGIC (in mg.h sense) hooks */
354 ithread_mg_get(pTHX_ SV *sv, MAGIC *mg)
356 ithread *thread = (ithread *)mg->mg_ptr;
357 SvIV_set(sv, PTR2IV(thread));
363 ithread_mg_free(pTHX_ SV *sv, MAGIC *mg)
365 ithread *thread = (ithread *)mg->mg_ptr;
366 MUTEX_LOCK(&thread->mutex);
367 S_ithread_free(aTHX_ thread); /* Releases MUTEX */
372 ithread_mg_dup(pTHX_ MAGIC *mg, CLONE_PARAMS *param)
374 S_ithread_count_inc(aTHX_ (ithread *)mg->mg_ptr);
378 MGVTBL ithread_vtbl = {
379 ithread_mg_get, /* get */
383 ithread_mg_free, /* free */
385 ithread_mg_dup /* dup */
389 /* Provided default, minimum and rational stack sizes */
391 S_good_stack_size(pTHX_ IV stack_size)
395 /* Use default stack size if no stack size specified */
397 return (MY_POOL.default_stack_size);
400 #ifdef PTHREAD_STACK_MIN
401 /* Can't use less than minimum */
402 if (stack_size < PTHREAD_STACK_MIN) {
403 if (ckWARN(WARN_THREADS)) {
404 Perl_warn(aTHX_ "Using minimum thread stack size of %" IVdf, (IV)PTHREAD_STACK_MIN);
406 return (PTHREAD_STACK_MIN);
410 /* Round up to page size boundary */
411 if (MY_POOL.page_size <= 0) {
412 #if defined(HAS_SYSCONF) && (defined(_SC_PAGESIZE) || defined(_SC_MMAP_PAGE_SIZE))
413 SETERRNO(0, SS_NORMAL);
415 MY_POOL.page_size = sysconf(_SC_PAGESIZE);
417 MY_POOL.page_size = sysconf(_SC_MMAP_PAGE_SIZE);
419 if ((long)MY_POOL.page_size < 0) {
421 SV * const error = get_sv("@", 0);
422 (void)SvUPGRADE(error, SVt_PV);
423 Perl_croak(aTHX_ "PANIC: sysconf: %s", SvPV_nolen(error));
425 Perl_croak(aTHX_ "PANIC: sysconf: pagesize unknown");
429 # ifdef HAS_GETPAGESIZE
430 MY_POOL.page_size = getpagesize();
432 # if defined(I_SYS_PARAM) && defined(PAGESIZE)
433 MY_POOL.page_size = PAGESIZE;
435 MY_POOL.page_size = 8192; /* A conservative default */
438 if (MY_POOL.page_size <= 0) {
439 Perl_croak(aTHX_ "PANIC: bad pagesize %" IVdf, (IV)MY_POOL.page_size);
443 stack_size = ((stack_size + (MY_POOL.page_size - 1)) / MY_POOL.page_size) * MY_POOL.page_size;
449 /* Starts executing the thread.
450 * Passed as the C level function to run in the new thread.
453 STATIC THREAD_RET_TYPE
454 S_ithread_run(LPVOID arg)
457 S_ithread_run(void * arg)
460 ithread *thread = (ithread *)arg;
463 int exit_app = 0; /* Thread terminated using 'exit' */
465 int died = 0; /* Thread terminated abnormally */
469 dTHXa(thread->interp);
473 /* Blocked until ->create() call finishes */
474 MUTEX_LOCK(&thread->mutex);
475 MUTEX_UNLOCK(&thread->mutex);
477 PERL_SET_CONTEXT(thread->interp);
478 S_ithread_set(aTHX_ thread);
481 /* Thread starts with most signals blocked - restore the signal mask from
482 * the ithread struct.
484 S_set_sigmask(&thread->initial_sigmask);
487 PL_perl_destruct_level = 2;
490 AV *params = thread->params;
491 int len = (int)av_len(params)+1;
498 /* Put args on the stack */
500 for (ii=0; ii < len; ii++) {
501 XPUSHs(av_shift(params));
505 oldscope = PL_scopestack_ix;
508 /* Run the specified function */
509 len = (int)call_sv(thread->init_function, thread->gimme|G_EVAL);
510 } else if (jmp_rc == 2) {
513 exit_code = STATUS_CURRENT;
514 while (PL_scopestack_ix > oldscope) {
521 /* The interpreter is finished, so this thread can stop receiving
522 * signals. This way, our signal handler doesn't get called in the
523 * middle of our parent thread calling perl_destruct()...
525 S_block_most_signals(NULL);
528 /* Remove args from stack and put back in params array */
530 for (ii=len-1; ii >= 0; ii--) {
532 if (jmp_rc == 0 && (thread->gimme & G_WANT) != G_VOID) {
533 av_store(params, ii, SvREFCNT_inc(sv));
540 /* Check for abnormal termination */
542 died = PERL_ITHR_DIED;
543 thread->err = newSVsv(ERRSV);
544 /* If ERRSV is an object, remember the classname and then
545 * rebless into 'main' so it will survive 'cloning'
547 if (sv_isobject(thread->err)) {
548 thread->err_class = HvNAME(SvSTASH(SvRV(thread->err)));
549 sv_bless(thread->err, gv_stashpv("main", 0));
552 if (ckWARN_d(WARN_THREADS)) {
553 oldscope = PL_scopestack_ix;
556 /* Warn that thread died */
557 Perl_warn(aTHX_ "Thread %" UVuf " terminated abnormally: %" SVf, thread->tid, ERRSV);
558 } else if (jmp_rc == 2) {
559 /* Warn handler exited */
561 exit_code = STATUS_CURRENT;
562 while (PL_scopestack_ix > oldscope) {
570 /* Release function ref */
571 SvREFCNT_dec(thread->init_function);
572 thread->init_function = Nullsv;
575 PerlIO_flush((PerlIO *)NULL);
577 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
578 MUTEX_LOCK(&thread->mutex);
579 /* Mark as finished */
580 thread->state |= (PERL_ITHR_FINISHED | died);
581 /* Clear exit flag if required */
582 if (thread->state & PERL_ITHR_THREAD_EXIT_ONLY) {
586 /* Adjust thread status counts */
587 if (thread->state & PERL_ITHR_DETACHED) {
588 MY_POOL.detached_threads--;
590 MY_POOL.running_threads--;
591 MY_POOL.joinable_threads++;
593 MUTEX_UNLOCK(&thread->mutex);
594 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
596 /* Exit application if required */
598 oldscope = PL_scopestack_ix;
601 /* Warn if there are unjoined threads */
602 S_exit_warning(aTHX);
603 } else if (jmp_rc == 2) {
604 /* Warn handler exited */
605 exit_code = STATUS_CURRENT;
606 while (PL_scopestack_ix > oldscope) {
615 /* At this point, the interpreter may have been freed, so call
616 * free in the the context of of the 'main' interpreter which
617 * can't have been freed due to the veto_cleanup mechanism.
619 aTHX = MY_POOL.main_thread.interp;
621 MUTEX_LOCK(&thread->mutex);
622 S_ithread_free(aTHX_ thread); /* Releases MUTEX */
632 /* Type conversion helper functions */
635 S_ithread_to_SV(pTHX_ SV *obj, ithread *thread, char *classname, bool inc)
641 S_ithread_count_inc(aTHX_ thread);
647 sv = newSVrv(obj, classname);
648 sv_setiv(sv, PTR2IV(thread));
649 mg = sv_magicext(sv, Nullsv, PERL_MAGIC_shared_scalar, &ithread_vtbl, (char *)thread, 0);
650 mg->mg_flags |= MGf_DUP;
657 S_SV_to_ithread(pTHX_ SV *sv)
659 /* Argument is a thread */
661 return (INT2PTR(ithread *, SvIV(SvRV(sv))));
663 /* Argument is classname, therefore return current thread */
664 return (S_ithread_get(aTHX));
669 * Called in context of parent thread.
670 * Called with MY_POOL.create_destruct_mutex locked. (Unlocked on error.)
674 pTHX_ SV *init_function,
681 ithread *current_thread = S_ithread_get(aTHX);
683 #if PERL_VERSION <= 8 && PERL_SUBVERSION <= 7
684 SV **tmps_tmp = PL_tmps_stack;
685 IV tmps_ix = PL_tmps_ix;
688 int rc_stack_size = 0;
689 int rc_thread_create = 0;
693 /* Allocate thread structure in context of the main thread's interpreter */
695 PERL_SET_CONTEXT(MY_POOL.main_thread.interp);
696 thread = (ithread *)PerlMemShared_malloc(sizeof(ithread));
698 PERL_SET_CONTEXT(aTHX);
700 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
701 PerlLIO_write(PerlIO_fileno(Perl_error_log), PL_no_mem, strlen(PL_no_mem));
704 Zero(thread, 1, ithread);
706 /* Add to threads list */
707 thread->next = &MY_POOL.main_thread;
708 thread->prev = MY_POOL.main_thread.prev;
709 MY_POOL.main_thread.prev = thread;
710 thread->prev->next = thread;
711 MY_POOL.total_threads++;
713 /* 1 ref to be held by the local var 'thread' in S_ithread_run().
714 * 1 ref to be held by the threads object that we assume we will
715 * be embedded in upon our return.
716 * 1 ref to be the responsibility of join/detach, so we don't get
717 * freed until join/detach, even if no thread objects remain.
718 * This allows the following to work:
719 * { threads->create(sub{...}); } threads->object(1)->join;
723 /* Block new thread until ->create() call finishes */
724 MUTEX_INIT(&thread->mutex);
725 MUTEX_LOCK(&thread->mutex);
727 thread->tid = MY_POOL.tid_counter++;
728 thread->stack_size = S_good_stack_size(aTHX_ stack_size);
729 thread->gimme = gimme;
730 thread->state = exit_opt;
732 /* "Clone" our interpreter into the thread's interpreter.
733 * This gives thread access to "static data" and code.
735 PerlIO_flush((PerlIO *)NULL);
736 S_ithread_set(aTHX_ thread);
738 SAVEBOOL(PL_srand_called); /* Save this so it becomes the correct value */
739 PL_srand_called = FALSE; /* Set it to false so we can detect if it gets
740 set during the clone */
743 /* perl_clone() will leave us the new interpreter's context. This poses
744 * two problems for our signal handler. First, it sets the new context
745 * before the new interpreter struct is fully initialized, so our signal
746 * handler might find bogus data in the interpreter struct it gets.
747 * Second, even if the interpreter is initialized before a signal comes in,
748 * we would like to avoid that interpreter receiving notifications for
749 * signals (especially when they ought to be for the one running in this
750 * thread), until it is running in its own thread. Another problem is that
751 * the new thread will not have set the context until some time after it
752 * has started, so it won't be safe for our signal handler to run until
755 * So we block most signals here, so the new thread will inherit the signal
756 * mask, and unblock them right after the thread creation. The original
757 * mask is saved in the thread struct so that the new thread can restore
760 S_block_most_signals(&thread->initial_sigmask);
764 thread->interp = perl_clone(aTHX, CLONEf_KEEP_PTR_TABLE | CLONEf_CLONE_HOST);
766 thread->interp = perl_clone(aTHX, CLONEf_KEEP_PTR_TABLE);
769 /* perl_clone() leaves us in new interpreter's context. As it is tricky
770 * to spot an implicit aTHX, create a new scope with aTHX matching the
771 * context for the duration of our work for new interpreter.
774 CLONE_PARAMS clone_param;
776 dTHXa(thread->interp);
780 /* Here we remove END blocks since they should only run in the thread
783 SvREFCNT_dec(PL_endav);
786 clone_param.flags = 0;
787 if (SvPOK(init_function)) {
788 thread->init_function = newSV(0);
789 sv_copypv(thread->init_function, init_function);
791 thread->init_function =
792 SvREFCNT_inc(sv_dup(init_function, &clone_param));
795 thread->params = (AV *)sv_dup((SV *)params, &clone_param);
796 SvREFCNT_inc_void(thread->params);
798 #if PERL_VERSION <= 8 && PERL_SUBVERSION <= 7
799 /* The code below checks that anything living on the tmps stack and
800 * has been cloned (so it lives in the ptr_table) has a refcount
803 * If the refcount is 0 it means that a something on the stack/context
804 * was holding a reference to it and since we init_stacks() in
805 * perl_clone that won't get cleaned and we will get a leaked scalar.
806 * The reason it was cloned was that it lived on the @_ stack.
808 * Example of this can be found in bugreport 15837 where calls in the
809 * parameter list end up as a temp.
811 * As of 5.8.8 this is done in perl_clone.
813 while (tmps_ix > 0) {
814 SV* sv = (SV*)ptr_table_fetch(PL_ptr_table, tmps_tmp[tmps_ix]);
816 if (sv && SvREFCNT(sv) == 0) {
817 SvREFCNT_inc_void(sv);
823 SvTEMP_off(thread->init_function);
824 ptr_table_free(PL_ptr_table);
826 PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
828 S_ithread_set(aTHX_ current_thread);
829 PERL_SET_CONTEXT(aTHX);
831 /* Create/start the thread */
833 thread->handle = CreateThread(NULL,
834 (DWORD)thread->stack_size,
837 STACK_SIZE_PARAM_IS_A_RESERVATION,
841 STATIC pthread_attr_t attr;
842 STATIC int attr_inited = 0;
843 STATIC int attr_joinable = PTHREAD_CREATE_JOINABLE;
845 pthread_attr_init(&attr);
849 # ifdef PTHREAD_ATTR_SETDETACHSTATE
850 /* Threads start out joinable */
851 PTHREAD_ATTR_SETDETACHSTATE(&attr, attr_joinable);
854 # ifdef _POSIX_THREAD_ATTR_STACKSIZE
855 /* Set thread's stack size */
856 if (thread->stack_size > 0) {
857 rc_stack_size = pthread_attr_setstacksize(&attr, (size_t)thread->stack_size);
861 /* Create the thread */
862 if (! rc_stack_size) {
863 # ifdef OLD_PTHREADS_API
864 rc_thread_create = pthread_create(&thread->thr,
869 # if defined(HAS_PTHREAD_ATTR_SETSCOPE) && defined(PTHREAD_SCOPE_SYSTEM)
870 pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);
872 rc_thread_create = pthread_create(&thread->thr,
880 /* Now it's safe to accept signals, since we're in our own interpreter's
881 * context and we have created the thread.
883 S_set_sigmask(&thread->initial_sigmask);
886 # ifdef _POSIX_THREAD_ATTR_STACKSIZE
887 /* Try to get thread's actual stack size */
891 stacksize = pthread_attr_getstacksize(attr);
893 if (! pthread_attr_getstacksize(&attr, &stacksize))
896 thread->stack_size = (IV)stacksize;
903 /* Check for errors */
905 if (thread->handle == NULL) {
907 if (rc_stack_size || rc_thread_create) {
909 /* Must unlock mutex for destruct call */
910 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
911 sv_2mortal((SV *)params);
912 thread->state |= PERL_ITHR_NONVIABLE;
913 S_ithread_free(aTHX_ thread); /* Releases MUTEX */
915 if (ckWARN_d(WARN_THREADS)) {
917 Perl_warn(aTHX_ "Thread creation failed: pthread_attr_setstacksize(%" IVdf ") returned %d", thread->stack_size, rc_stack_size);
919 Perl_warn(aTHX_ "Thread creation failed: pthread_create returned %d", rc_thread_create);
926 MY_POOL.running_threads++;
927 sv_2mortal((SV *)params);
931 #endif /* USE_ITHREADS */
934 MODULE = threads PACKAGE = threads PREFIX = ithread_
944 SV *function_to_call;
950 SV *thread_exit_only;
956 if ((items >= 2) && SvROK(ST(1)) && SvTYPE(SvRV(ST(1)))==SVt_PVHV) {
958 Perl_croak(aTHX_ "Usage: threads->create(\\%%specs, function, ...)");
960 specs = (HV*)SvRV(ST(1));
964 Perl_croak(aTHX_ "Usage: threads->create(function, ...)");
970 if (sv_isobject(ST(0))) {
972 classname = HvNAME(SvSTASH(SvRV(ST(0))));
973 thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
974 MUTEX_LOCK(&thread->mutex);
975 stack_size = thread->stack_size;
976 exit_opt = thread->state & PERL_ITHR_THREAD_EXIT_ONLY;
977 MUTEX_UNLOCK(&thread->mutex);
979 /* threads->create() */
980 classname = (char *)SvPV_nolen(ST(0));
981 stack_size = MY_POOL.default_stack_size;
982 thread_exit_only = get_sv("threads::thread_exit_only", GV_ADD);
983 exit_opt = (SvTRUE(thread_exit_only))
984 ? PERL_ITHR_THREAD_EXIT_ONLY : 0;
987 function_to_call = ST(idx+1);
992 if (hv_exists(specs, "stack", 5)) {
993 stack_size = SvIV(*hv_fetch(specs, "stack", 5, 0));
994 } else if (hv_exists(specs, "stacksize", 9)) {
995 stack_size = SvIV(*hv_fetch(specs, "stacksize", 9, 0));
996 } else if (hv_exists(specs, "stack_size", 10)) {
997 stack_size = SvIV(*hv_fetch(specs, "stack_size", 10, 0));
1001 if (hv_exists(specs, "context", 7)) {
1002 str = (char *)SvPV_nolen(*hv_fetch(specs, "context", 7, 0));
1019 Perl_croak(aTHX_ "Invalid context: %s", str);
1021 } else if (hv_exists(specs, "array", 5)) {
1022 if (SvTRUE(*hv_fetch(specs, "array", 5, 0))) {
1025 } else if (hv_exists(specs, "list", 4)) {
1026 if (SvTRUE(*hv_fetch(specs, "list", 4, 0))) {
1029 } else if (hv_exists(specs, "scalar", 6)) {
1030 if (SvTRUE(*hv_fetch(specs, "scalar", 6, 0))) {
1033 } else if (hv_exists(specs, "void", 4)) {
1034 if (SvTRUE(*hv_fetch(specs, "void", 4, 0))) {
1039 /* exit => thread_only */
1040 if (hv_exists(specs, "exit", 4)) {
1041 str = (char *)SvPV_nolen(*hv_fetch(specs, "exit", 4, 0));
1042 exit_opt = (*str == 't' || *str == 'T')
1043 ? PERL_ITHR_THREAD_EXIT_ONLY : 0;
1046 if (context == -1) {
1047 context = GIMME_V; /* Implicit context */
1049 context |= (GIMME_V & (~(G_ARRAY|G_SCALAR|G_VOID)));
1055 for (ii=2; ii < items ; ii++) {
1056 av_push(params, SvREFCNT_inc(ST(idx+ii)));
1061 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
1062 thread = S_ithread_create(aTHX_ function_to_call,
1068 XSRETURN_UNDEF; /* Mutex already unlocked */
1070 ST(0) = sv_2mortal(S_ithread_to_SV(aTHX_ Nullsv, thread, classname, FALSE));
1071 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
1073 /* Let thread run */
1074 MUTEX_UNLOCK(&thread->mutex);
1076 /* XSRETURN(1); - implied */
1086 int want_running = 0;
1090 /* Class method only */
1092 Perl_croak(aTHX_ "Usage: threads->list(...)");
1094 classname = (char *)SvPV_nolen(ST(0));
1096 /* Calling context */
1097 list_context = (GIMME_V == G_ARRAY);
1099 /* Running or joinable parameter */
1101 want_running = SvTRUE(ST(1));
1104 /* Walk through threads list */
1105 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
1106 for (thread = MY_POOL.main_thread.next;
1107 thread != &MY_POOL.main_thread;
1108 thread = thread->next)
1110 MUTEX_LOCK(&thread->mutex);
1111 state = thread->state;
1112 MUTEX_UNLOCK(&thread->mutex);
1114 /* Ignore detached or joined threads */
1115 if (state & PERL_ITHR_UNCALLABLE) {
1119 /* Filter per parameter */
1122 if (state & PERL_ITHR_FINISHED) {
1123 continue; /* Not running */
1126 if (! (state & PERL_ITHR_FINISHED)) {
1127 continue; /* Still running - not joinable yet */
1132 /* Push object on stack if list context */
1134 XPUSHs(sv_2mortal(S_ithread_to_SV(aTHX_ Nullsv, thread, classname, TRUE)));
1138 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
1139 /* If scalar context, send back count */
1140 if (! list_context) {
1151 /* Class method only */
1152 if ((items != 1) || SvROK(ST(0))) {
1153 Perl_croak(aTHX_ "Usage: threads->self()");
1155 classname = (char *)SvPV_nolen(ST(0));
1157 thread = S_ithread_get(aTHX);
1159 ST(0) = sv_2mortal(S_ithread_to_SV(aTHX_ Nullsv, thread, classname, TRUE));
1160 /* XSRETURN(1); - implied */
1168 PERL_UNUSED_VAR(items);
1169 thread = S_SV_to_ithread(aTHX_ ST(0));
1170 XST_mUV(0, thread->tid);
1171 /* XSRETURN(1); - implied */
1178 ithread *current_thread;
1189 /* Object method only */
1190 if ((items != 1) || ! sv_isobject(ST(0))) {
1191 Perl_croak(aTHX_ "Usage: $thr->join()");
1194 /* Check if the thread is joinable and not ourselves */
1195 thread = S_SV_to_ithread(aTHX_ ST(0));
1196 current_thread = S_ithread_get(aTHX);
1198 MUTEX_LOCK(&thread->mutex);
1199 if ((join_err = (thread->state & PERL_ITHR_UNCALLABLE))) {
1200 MUTEX_UNLOCK(&thread->mutex);
1201 Perl_croak(aTHX_ (join_err & PERL_ITHR_DETACHED)
1202 ? "Cannot join a detached thread"
1203 : "Thread already joined");
1204 } else if (thread->tid == current_thread->tid) {
1205 MUTEX_UNLOCK(&thread->mutex);
1206 Perl_croak(aTHX_ "Cannot join self");
1209 /* Mark as joined */
1210 thread->state |= PERL_ITHR_JOINED;
1211 MUTEX_UNLOCK(&thread->mutex);
1213 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
1214 MY_POOL.joinable_threads--;
1215 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
1217 /* Join the thread */
1219 if (WaitForSingleObject(thread->handle, INFINITE) != WAIT_OBJECT_0) {
1220 /* Timeout/abandonment unexpected here; check $^E */
1221 Perl_croak(aTHX_ "PANIC: underlying join failed");
1224 if ((rc_join = pthread_join(thread->thr, &retval)) != 0) {
1225 /* In progress/deadlock/unknown unexpected here; check $! */
1227 Perl_croak(aTHX_ "PANIC: underlying join failed");
1231 MUTEX_LOCK(&thread->mutex);
1232 /* Get the return value from the call_sv */
1233 /* Objects do not survive this process - FIXME */
1234 if ((thread->gimme & G_WANT) != G_VOID) {
1236 PerlInterpreter *other_perl;
1237 CLONE_PARAMS clone_params;
1239 params_copy = thread->params;
1240 other_perl = thread->interp;
1241 clone_params.stashes = newAV();
1242 clone_params.flags = CLONEf_JOIN_IN;
1243 PL_ptr_table = ptr_table_new();
1244 S_ithread_set(aTHX_ thread);
1245 /* Ensure 'meaningful' addresses retain their meaning */
1246 ptr_table_store(PL_ptr_table, &other_perl->Isv_undef, &PL_sv_undef);
1247 ptr_table_store(PL_ptr_table, &other_perl->Isv_no, &PL_sv_no);
1248 ptr_table_store(PL_ptr_table, &other_perl->Isv_yes, &PL_sv_yes);
1249 params = (AV *)sv_dup((SV*)params_copy, &clone_params);
1250 S_ithread_set(aTHX_ current_thread);
1251 SvREFCNT_dec(clone_params.stashes);
1252 SvREFCNT_inc_void(params);
1253 ptr_table_free(PL_ptr_table);
1254 PL_ptr_table = NULL;
1257 /* If thread didn't die, then we can free its interpreter */
1258 if (! (thread->state & PERL_ITHR_DIED)) {
1259 S_ithread_clear(aTHX_ thread);
1261 S_ithread_free(aTHX_ thread); /* Releases MUTEX */
1263 /* If no return values, then just return */
1268 /* Put return values on stack */
1269 len = (int)AvFILL(params);
1270 for (ii=0; ii <= len; ii++) {
1271 SV* param = av_shift(params);
1272 XPUSHs(sv_2mortal(param));
1275 /* Free return value array */
1276 SvREFCNT_dec(params);
1282 PERL_UNUSED_VAR(items);
1293 PERL_UNUSED_VAR(items);
1295 /* Detach the thread */
1296 thread = S_SV_to_ithread(aTHX_ ST(0));
1297 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
1298 MUTEX_LOCK(&thread->mutex);
1299 if (! (detach_err = (thread->state & PERL_ITHR_UNCALLABLE))) {
1300 /* Thread is detachable */
1301 thread->state |= PERL_ITHR_DETACHED;
1303 /* Windows has no 'detach thread' function */
1305 PERL_THREAD_DETACH(thread->thr);
1307 if (thread->state & PERL_ITHR_FINISHED) {
1308 MY_POOL.joinable_threads--;
1310 MY_POOL.running_threads--;
1311 MY_POOL.detached_threads++;
1314 MUTEX_UNLOCK(&thread->mutex);
1315 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
1318 Perl_croak(aTHX_ (detach_err & PERL_ITHR_DETACHED)
1319 ? "Thread already detached"
1320 : "Cannot detach a joined thread");
1323 /* If thread is finished and didn't die,
1324 * then we can free its interpreter */
1325 MUTEX_LOCK(&thread->mutex);
1326 if ((thread->state & PERL_ITHR_FINISHED) &&
1327 ! (thread->state & PERL_ITHR_DIED))
1329 S_ithread_clear(aTHX_ thread);
1331 S_ithread_free(aTHX_ thread); /* Releases MUTEX */
1341 /* Must have safe signals */
1342 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG) {
1343 Perl_croak(aTHX_ "Cannot signal threads without safe signals");
1346 /* Object method only */
1347 if ((items != 2) || ! sv_isobject(ST(0))) {
1348 Perl_croak(aTHX_ "Usage: $thr->kill('SIG...')");
1352 sig_name = SvPV_nolen(ST(1));
1353 if (isALPHA(*sig_name)) {
1354 if (*sig_name == 'S' && sig_name[1] == 'I' && sig_name[2] == 'G') {
1357 if ((signal = whichsig(sig_name)) < 0) {
1358 Perl_croak(aTHX_ "Unrecognized signal name: %s", sig_name);
1361 signal = SvIV(ST(1));
1364 /* Set the signal for the thread */
1365 thread = S_SV_to_ithread(aTHX_ ST(0));
1366 MUTEX_LOCK(&thread->mutex);
1367 if (thread->interp) {
1368 dTHXa(thread->interp);
1369 PL_psig_pend[signal]++;
1372 MUTEX_UNLOCK(&thread->mutex);
1374 /* Return the thread to allow for method chaining */
1376 /* XSRETURN(1); - implied */
1380 ithread_DESTROY(...)
1382 PERL_UNUSED_VAR(items);
1383 sv_unmagic(SvRV(ST(0)), PERL_MAGIC_shared_scalar);
1391 PERL_UNUSED_VAR(items);
1393 /* Compares TIDs to determine thread equality */
1394 if (sv_isobject(ST(0)) && sv_isobject(ST(1))) {
1395 ithread *thr1 = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1396 ithread *thr2 = INT2PTR(ithread *, SvIV(SvRV(ST(1))));
1397 are_equal = (thr1->tid == thr2->tid);
1402 /* Return 0 on false for backward compatibility */
1405 /* XSRETURN(1); - implied */
1419 /* Class method only */
1421 Perl_croak(aTHX_ "Usage: threads->object($tid)");
1423 classname = (char *)SvPV_nolen(ST(0));
1425 /* Turn $tid from PVLV to SV if needed (bug #73330) */
1429 if ((items < 2) || ! SvOK(arg)) {
1433 /* threads->object($tid) */
1436 /* If current thread wants its own object, then behave the same as
1438 thread = S_ithread_get(aTHX);
1439 if (thread->tid == tid) {
1440 ST(0) = sv_2mortal(S_ithread_to_SV(aTHX_ Nullsv, thread, classname, TRUE));
1444 /* Walk through threads list */
1445 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
1446 for (thread = MY_POOL.main_thread.next;
1447 thread != &MY_POOL.main_thread;
1448 thread = thread->next)
1451 if (thread->tid == tid) {
1452 /* Ignore if detached or joined */
1453 MUTEX_LOCK(&thread->mutex);
1454 state = thread->state;
1455 MUTEX_UNLOCK(&thread->mutex);
1456 if (! (state & PERL_ITHR_UNCALLABLE)) {
1457 /* Put object on stack */
1458 ST(0) = sv_2mortal(S_ithread_to_SV(aTHX_ Nullsv, thread, classname, TRUE));
1464 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
1470 /* XSRETURN(1); - implied */
1474 ithread__handle(...);
1478 PERL_UNUSED_VAR(items);
1479 thread = S_SV_to_ithread(aTHX_ ST(0));
1481 XST_mUV(0, PTR2UV(&thread->handle));
1483 XST_mUV(0, PTR2UV(&thread->thr));
1485 /* XSRETURN(1); - implied */
1489 ithread_get_stack_size(...)
1494 PERL_UNUSED_VAR(items);
1495 if (sv_isobject(ST(0))) {
1496 /* $thr->get_stack_size() */
1497 ithread *thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1498 stack_size = thread->stack_size;
1500 /* threads->get_stack_size() */
1501 stack_size = MY_POOL.default_stack_size;
1503 XST_mIV(0, stack_size);
1504 /* XSRETURN(1); - implied */
1508 ithread_set_stack_size(...)
1514 Perl_croak(aTHX_ "Usage: threads->set_stack_size($size)");
1516 if (sv_isobject(ST(0))) {
1517 Perl_croak(aTHX_ "Cannot change stack size of an existing thread");
1519 if (! looks_like_number(ST(1))) {
1520 Perl_croak(aTHX_ "Stack size must be numeric");
1523 old_size = MY_POOL.default_stack_size;
1524 MY_POOL.default_stack_size = S_good_stack_size(aTHX_ SvIV(ST(1)));
1525 XST_mIV(0, old_size);
1526 /* XSRETURN(1); - implied */
1530 ithread_is_running(...)
1534 /* Object method only */
1535 if ((items != 1) || ! sv_isobject(ST(0))) {
1536 Perl_croak(aTHX_ "Usage: $thr->is_running()");
1539 thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1540 MUTEX_LOCK(&thread->mutex);
1541 ST(0) = (thread->state & PERL_ITHR_FINISHED) ? &PL_sv_no : &PL_sv_yes;
1542 MUTEX_UNLOCK(&thread->mutex);
1543 /* XSRETURN(1); - implied */
1547 ithread_is_detached(...)
1551 PERL_UNUSED_VAR(items);
1552 thread = S_SV_to_ithread(aTHX_ ST(0));
1553 MUTEX_LOCK(&thread->mutex);
1554 ST(0) = (thread->state & PERL_ITHR_DETACHED) ? &PL_sv_yes : &PL_sv_no;
1555 MUTEX_UNLOCK(&thread->mutex);
1556 /* XSRETURN(1); - implied */
1560 ithread_is_joinable(...)
1564 /* Object method only */
1565 if ((items != 1) || ! sv_isobject(ST(0))) {
1566 Perl_croak(aTHX_ "Usage: $thr->is_joinable()");
1569 thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1570 MUTEX_LOCK(&thread->mutex);
1571 ST(0) = ((thread->state & PERL_ITHR_FINISHED) &&
1572 ! (thread->state & PERL_ITHR_UNCALLABLE))
1573 ? &PL_sv_yes : &PL_sv_no;
1574 MUTEX_UNLOCK(&thread->mutex);
1575 /* XSRETURN(1); - implied */
1579 ithread_wantarray(...)
1583 PERL_UNUSED_VAR(items);
1584 thread = S_SV_to_ithread(aTHX_ ST(0));
1585 ST(0) = ((thread->gimme & G_WANT) == G_ARRAY) ? &PL_sv_yes :
1586 ((thread->gimme & G_WANT) == G_VOID) ? &PL_sv_undef
1587 /* G_SCALAR */ : &PL_sv_no;
1588 /* XSRETURN(1); - implied */
1592 ithread_set_thread_exit_only(...)
1597 Perl_croak(aTHX_ "Usage: ->set_thread_exit_only(boolean)");
1599 thread = S_SV_to_ithread(aTHX_ ST(0));
1600 MUTEX_LOCK(&thread->mutex);
1601 if (SvTRUE(ST(1))) {
1602 thread->state |= PERL_ITHR_THREAD_EXIT_ONLY;
1604 thread->state &= ~PERL_ITHR_THREAD_EXIT_ONLY;
1606 MUTEX_UNLOCK(&thread->mutex);
1615 /* Object method only */
1616 if ((items != 1) || ! sv_isobject(ST(0))) {
1617 Perl_croak(aTHX_ "Usage: $thr->err()");
1620 thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1621 MUTEX_LOCK(&thread->mutex);
1623 /* If thread died, then clone the error into the calling thread */
1624 if (thread->state & PERL_ITHR_DIED) {
1625 PerlInterpreter *other_perl;
1626 CLONE_PARAMS clone_params;
1627 ithread *current_thread;
1629 other_perl = thread->interp;
1630 clone_params.stashes = newAV();
1631 clone_params.flags = CLONEf_JOIN_IN;
1632 PL_ptr_table = ptr_table_new();
1633 current_thread = S_ithread_get(aTHX);
1634 S_ithread_set(aTHX_ thread);
1635 /* Ensure 'meaningful' addresses retain their meaning */
1636 ptr_table_store(PL_ptr_table, &other_perl->Isv_undef, &PL_sv_undef);
1637 ptr_table_store(PL_ptr_table, &other_perl->Isv_no, &PL_sv_no);
1638 ptr_table_store(PL_ptr_table, &other_perl->Isv_yes, &PL_sv_yes);
1639 err = sv_dup(thread->err, &clone_params);
1640 S_ithread_set(aTHX_ current_thread);
1641 SvREFCNT_dec(clone_params.stashes);
1642 SvREFCNT_inc_void(err);
1643 /* If error was an object, bless it into the correct class */
1644 if (thread->err_class) {
1645 sv_bless(err, gv_stashpv(thread->err_class, 1));
1647 ptr_table_free(PL_ptr_table);
1648 PL_ptr_table = NULL;
1651 MUTEX_UNLOCK(&thread->mutex);
1657 ST(0) = sv_2mortal(err);
1658 /* XSRETURN(1); - implied */
1661 #endif /* USE_ITHREADS */
1667 SV *my_pool_sv = *hv_fetch(PL_modglobal, MY_POOL_KEY,
1668 sizeof(MY_POOL_KEY)-1, TRUE);
1669 my_pool_t *my_poolp = (my_pool_t*)SvPVX(newSV(sizeof(my_pool_t)-1));
1673 Zero(my_poolp, 1, my_pool_t);
1674 sv_setuv(my_pool_sv, PTR2UV(my_poolp));
1676 PL_perl_destruct_level = 2;
1677 MUTEX_INIT(&MY_POOL.create_destruct_mutex);
1678 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
1680 PL_threadhook = &Perl_ithread_hook;
1682 MY_POOL.tid_counter = 1;
1683 # ifdef THREAD_CREATE_NEEDS_STACK
1684 MY_POOL.default_stack_size = THREAD_CREATE_NEEDS_STACK;
1687 /* The 'main' thread is thread 0.
1688 * It is detached (unjoinable) and immortal.
1691 MUTEX_INIT(&MY_POOL.main_thread.mutex);
1693 /* Head of the threads list */
1694 MY_POOL.main_thread.next = &MY_POOL.main_thread;
1695 MY_POOL.main_thread.prev = &MY_POOL.main_thread;
1697 MY_POOL.main_thread.count = 1; /* Immortal */
1699 MY_POOL.main_thread.interp = aTHX;
1700 MY_POOL.main_thread.state = PERL_ITHR_DETACHED; /* Detached */
1701 MY_POOL.main_thread.stack_size = MY_POOL.default_stack_size;
1703 MY_POOL.main_thread.thr = GetCurrentThreadId();
1705 MY_POOL.main_thread.thr = pthread_self();
1708 S_ithread_set(aTHX_ &MY_POOL.main_thread);
1709 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
1710 #endif /* USE_ITHREADS */