1 #define PERL_NO_GET_CONTEXT
5 /* Workaround for XSUB.h bug under WIN32 */
8 # if !defined(__BORLANDC__)
9 # define setjmp(x) _setjmp(x)
13 # define NEED_PL_signals
14 # define NEED_newRV_noinc
15 # define NEED_sv_2pv_flags
24 /* Supposed to be in Winbase.h */
25 # ifndef STACK_SIZE_PARAM_IS_A_RESERVATION
26 # define STACK_SIZE_PARAM_IS_A_RESERVATION 0x00010000
28 # include <win32thread.h>
31 typedef perl_os_thread pthread_t;
36 # define PERL_THREAD_SETSPECIFIC(k,v) pthread_setspecific(k,v)
37 # ifdef OLD_PTHREADS_API
38 # define PERL_THREAD_DETACH(t) pthread_detach(&(t))
40 # define PERL_THREAD_DETACH(t) pthread_detach((t))
43 #if !defined(HAS_GETPAGESIZE) && defined(I_SYS_PARAM)
44 # include <sys/param.h>
47 /* Values for 'state' member */
48 #define PERL_ITHR_DETACHED 1 /* Thread has been detached */
49 #define PERL_ITHR_JOINED 2 /* Thread has been joined */
50 #define PERL_ITHR_FINISHED 4 /* Thread has finished execution */
51 #define PERL_ITHR_THREAD_EXIT_ONLY 8 /* exit() only exits current thread */
52 #define PERL_ITHR_NONVIABLE 16 /* Thread creation failed */
53 #define PERL_ITHR_DIED 32 /* Thread finished by dying */
55 #define PERL_ITHR_UNCALLABLE (PERL_ITHR_DETACHED|PERL_ITHR_JOINED)
58 typedef struct _ithread {
59 struct _ithread *next; /* Next thread in the list */
60 struct _ithread *prev; /* Prev thread in the list */
61 PerlInterpreter *interp; /* The threads interpreter */
62 UV tid; /* Threads module's thread id */
63 perl_mutex mutex; /* Mutex for updating things in this struct */
64 int count; /* Reference count. See S_ithread_create. */
65 int state; /* Detached, joined, finished, etc. */
66 int gimme; /* Context of create */
67 SV *init_function; /* Code to run */
68 SV *params; /* Args to pass function */
70 DWORD thr; /* OS's idea if thread id */
71 HANDLE handle; /* OS's waitable handle */
73 pthread_t thr; /* OS's handle for the thread */
76 SV *err; /* Error from abnormally terminated thread */
77 char *err_class; /* Error object's classname if applicable */
79 sigset_t initial_sigmask; /* Thread wakes up with signals blocked */
84 #define MY_CXT_KEY "threads::_cxt" XS_VERSION
87 /* Used by Perl interpreter for thread context switching */
94 #define MY_POOL_KEY "threads::_pool" XS_VERSION
97 /* Structure for 'main' thread
98 * Also forms the 'base' for the doubly-linked list of threads */
101 /* Protects the creation and destruction of threads*/
102 perl_mutex create_destruct_mutex;
109 IV default_stack_size;
114 SV *my_pool_sv = *hv_fetch(PL_modglobal, MY_POOL_KEY, \
115 sizeof(MY_POOL_KEY)-1, TRUE); \
116 my_pool_t *my_poolp = INT2PTR(my_pool_t*, SvUV(my_pool_sv))
118 #define MY_POOL (*my_poolp)
121 /* Block most signals for calling thread, setting the old signal mask to
122 * oldmask, if it is not NULL */
124 S_block_most_signals(sigset_t *oldmask)
128 sigfillset(&newmask);
129 /* Don't block certain "important" signals (stolen from mg.c) */
131 sigdelset(&newmask, SIGILL);
134 sigdelset(&newmask, SIGBUS);
137 sigdelset(&newmask, SIGSEGV);
141 /* no per-thread blocking available */
142 return sigprocmask(SIG_BLOCK, &newmask, oldmask);
144 return pthread_sigmask(SIG_BLOCK, &newmask, oldmask);
148 /* Set the signal mask for this thread to newmask */
150 S_set_sigmask(sigset_t *newmask)
153 return sigprocmask(SIG_SETMASK, newmask, NULL);
155 return pthread_sigmask(SIG_SETMASK, newmask, NULL);
160 /* Used by Perl interpreter for thread context switching */
162 S_ithread_set(pTHX_ ithread *thread)
165 MY_CXT.context = thread;
172 return (MY_CXT.context);
176 /* Free any data (such as the Perl interpreter) attached to an ithread
177 * structure. This is a bit like undef on SVs, where the SV isn't freed,
178 * but the PVX is. Must be called with thread->mutex already locked. Also,
179 * must be called with MY_POOL.create_destruct_mutex unlocked as destruction
180 * of the interpreter can lead to recursive destruction calls that could
181 * lead to a deadlock on that mutex.
184 S_ithread_clear(pTHX_ ithread *thread)
186 PerlInterpreter *interp;
191 assert(((thread->state & PERL_ITHR_FINISHED) &&
192 (thread->state & PERL_ITHR_UNCALLABLE))
194 (thread->state & PERL_ITHR_NONVIABLE));
197 /* We temporarily set the interpreter context to the interpreter being
198 * destroyed. It's in no condition to handle signals while it's being
201 S_block_most_signals(&origmask);
204 interp = thread->interp;
208 PERL_SET_CONTEXT(interp);
209 S_ithread_set(aTHX_ thread);
211 SvREFCNT_dec(thread->params);
212 thread->params = Nullsv;
215 SvREFCNT_dec(thread->err);
216 thread->err = Nullsv;
219 perl_destruct(interp);
221 thread->interp = NULL;
224 PERL_SET_CONTEXT(aTHX);
226 S_set_sigmask(&origmask);
231 /* Decrement the refcount of an ithread, and if it reaches zero, free it.
232 * Must be called with the mutex held.
233 * On return, mutex is released (or destroyed).
236 S_ithread_free(pTHX_ ithread *thread)
243 if (! (thread->state & PERL_ITHR_NONVIABLE)) {
244 assert(thread->count > 0);
245 if (--thread->count > 0) {
246 MUTEX_UNLOCK(&thread->mutex);
249 assert((thread->state & PERL_ITHR_FINISHED) &&
250 (thread->state & PERL_ITHR_UNCALLABLE));
252 MUTEX_UNLOCK(&thread->mutex);
254 /* Main thread (0) is immortal and should never get here */
255 assert(thread->tid != 0);
257 /* Remove from circular list of threads */
258 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
259 assert(thread->prev && thread->next);
260 thread->next->prev = thread->prev;
261 thread->prev->next = thread->next;
264 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
266 /* Thread is now disowned */
267 MUTEX_LOCK(&thread->mutex);
268 S_ithread_clear(aTHX_ thread);
271 handle = thread->handle;
272 thread->handle = NULL;
274 MUTEX_UNLOCK(&thread->mutex);
275 MUTEX_DESTROY(&thread->mutex);
283 PerlMemShared_free(thread);
285 /* total_threads >= 1 is used to veto cleanup by the main thread,
286 * should it happen to exit while other threads still exist.
287 * Decrement this as the very last thing in the thread's existence.
288 * Otherwise, MY_POOL and global state such as PL_op_mutex may get
289 * freed while we're still using it.
291 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
292 MY_POOL.total_threads--;
293 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
298 S_ithread_count_inc(pTHX_ ithread *thread)
300 MUTEX_LOCK(&thread->mutex);
302 MUTEX_UNLOCK(&thread->mutex);
306 /* Warn if exiting with any unjoined threads */
310 int veto_cleanup, warn;
313 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
314 veto_cleanup = (MY_POOL.total_threads > 0);
315 warn = (MY_POOL.running_threads || MY_POOL.joinable_threads);
316 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
319 if (ckWARN_d(WARN_THREADS)) {
320 Perl_warn(aTHX_ "Perl exited with active threads:\n\t%"
321 IVdf " running and unjoined\n\t%"
322 IVdf " finished and unjoined\n\t%"
323 IVdf " running and detached\n",
324 MY_POOL.running_threads,
325 MY_POOL.joinable_threads,
326 MY_POOL.detached_threads);
330 return (veto_cleanup);
334 /* Called from perl_destruct() in each thread. If it's the main thread,
335 * stop it from freeing everything if there are other threads still running.
338 Perl_ithread_hook(pTHX)
341 return ((aTHX == MY_POOL.main_thread.interp) ? S_exit_warning(aTHX) : 0);
345 /* MAGIC (in mg.h sense) hooks */
348 ithread_mg_get(pTHX_ SV *sv, MAGIC *mg)
350 ithread *thread = (ithread *)mg->mg_ptr;
351 SvIV_set(sv, PTR2IV(thread));
357 ithread_mg_free(pTHX_ SV *sv, MAGIC *mg)
359 ithread *thread = (ithread *)mg->mg_ptr;
360 MUTEX_LOCK(&thread->mutex);
361 S_ithread_free(aTHX_ thread); /* Releases MUTEX */
366 ithread_mg_dup(pTHX_ MAGIC *mg, CLONE_PARAMS *param)
368 S_ithread_count_inc(aTHX_ (ithread *)mg->mg_ptr);
372 MGVTBL ithread_vtbl = {
373 ithread_mg_get, /* get */
377 ithread_mg_free, /* free */
379 ithread_mg_dup /* dup */
383 /* Provided default, minimum and rational stack sizes */
385 S_good_stack_size(pTHX_ IV stack_size)
389 /* Use default stack size if no stack size specified */
391 return (MY_POOL.default_stack_size);
394 #ifdef PTHREAD_STACK_MIN
395 /* Can't use less than minimum */
396 if (stack_size < PTHREAD_STACK_MIN) {
397 if (ckWARN(WARN_THREADS)) {
398 Perl_warn(aTHX_ "Using minimum thread stack size of %" IVdf, (IV)PTHREAD_STACK_MIN);
400 return (PTHREAD_STACK_MIN);
404 /* Round up to page size boundary */
405 if (MY_POOL.page_size <= 0) {
406 #if defined(HAS_SYSCONF) && (defined(_SC_PAGESIZE) || defined(_SC_MMAP_PAGE_SIZE))
407 SETERRNO(0, SS_NORMAL);
409 MY_POOL.page_size = sysconf(_SC_PAGESIZE);
411 MY_POOL.page_size = sysconf(_SC_MMAP_PAGE_SIZE);
413 if ((long)MY_POOL.page_size < 0) {
415 SV * const error = get_sv("@", 0);
416 (void)SvUPGRADE(error, SVt_PV);
417 Perl_croak(aTHX_ "PANIC: sysconf: %s", SvPV_nolen(error));
419 Perl_croak(aTHX_ "PANIC: sysconf: pagesize unknown");
423 # ifdef HAS_GETPAGESIZE
424 MY_POOL.page_size = getpagesize();
426 # if defined(I_SYS_PARAM) && defined(PAGESIZE)
427 MY_POOL.page_size = PAGESIZE;
429 MY_POOL.page_size = 8192; /* A conservative default */
432 if (MY_POOL.page_size <= 0) {
433 Perl_croak(aTHX_ "PANIC: bad pagesize %" IVdf, (IV)MY_POOL.page_size);
437 stack_size = ((stack_size + (MY_POOL.page_size - 1)) / MY_POOL.page_size) * MY_POOL.page_size;
443 /* Starts executing the thread.
444 * Passed as the C level function to run in the new thread.
447 STATIC THREAD_RET_TYPE
448 S_ithread_run(LPVOID arg)
451 S_ithread_run(void * arg)
454 ithread *thread = (ithread *)arg;
457 int exit_app = 0; /* Thread terminated using 'exit' */
459 int died = 0; /* Thread terminated abnormally */
463 dTHXa(thread->interp);
467 /* Blocked until ->create() call finishes */
468 MUTEX_LOCK(&thread->mutex);
469 MUTEX_UNLOCK(&thread->mutex);
471 PERL_SET_CONTEXT(thread->interp);
472 S_ithread_set(aTHX_ thread);
475 /* Thread starts with most signals blocked - restore the signal mask from
476 * the ithread struct.
478 S_set_sigmask(&thread->initial_sigmask);
481 PL_perl_destruct_level = 2;
484 AV *params = (AV *)SvRV(thread->params);
485 int len = (int)av_len(params)+1;
492 /* Put args on the stack */
494 for (ii=0; ii < len; ii++) {
495 XPUSHs(av_shift(params));
499 oldscope = PL_scopestack_ix;
502 /* Run the specified function */
503 len = (int)call_sv(thread->init_function, thread->gimme|G_EVAL);
504 } else if (jmp_rc == 2) {
507 exit_code = STATUS_CURRENT;
508 while (PL_scopestack_ix > oldscope) {
515 /* The interpreter is finished, so this thread can stop receiving
516 * signals. This way, our signal handler doesn't get called in the
517 * middle of our parent thread calling perl_destruct()...
519 S_block_most_signals(NULL);
522 /* Remove args from stack and put back in params array */
524 for (ii=len-1; ii >= 0; ii--) {
526 if (jmp_rc == 0 && (thread->gimme & G_WANT) != G_VOID) {
527 av_store(params, ii, SvREFCNT_inc(sv));
534 /* Check for abnormal termination */
536 died = PERL_ITHR_DIED;
537 thread->err = newSVsv(ERRSV);
538 /* If ERRSV is an object, remember the classname and then
539 * rebless into 'main' so it will survive 'cloning'
541 if (sv_isobject(thread->err)) {
542 thread->err_class = HvNAME(SvSTASH(SvRV(thread->err)));
543 sv_bless(thread->err, gv_stashpv("main", 0));
546 if (ckWARN_d(WARN_THREADS)) {
547 oldscope = PL_scopestack_ix;
550 /* Warn that thread died */
551 Perl_warn(aTHX_ "Thread %" UVuf " terminated abnormally: %" SVf, thread->tid, ERRSV);
552 } else if (jmp_rc == 2) {
553 /* Warn handler exited */
555 exit_code = STATUS_CURRENT;
556 while (PL_scopestack_ix > oldscope) {
564 /* Release function ref */
565 SvREFCNT_dec(thread->init_function);
566 thread->init_function = Nullsv;
569 PerlIO_flush((PerlIO *)NULL);
571 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
572 MUTEX_LOCK(&thread->mutex);
573 /* Mark as finished */
574 thread->state |= (PERL_ITHR_FINISHED | died);
575 /* Clear exit flag if required */
576 if (thread->state & PERL_ITHR_THREAD_EXIT_ONLY) {
580 /* Adjust thread status counts */
581 if (thread->state & PERL_ITHR_DETACHED) {
582 MY_POOL.detached_threads--;
584 MY_POOL.running_threads--;
585 MY_POOL.joinable_threads++;
587 MUTEX_UNLOCK(&thread->mutex);
588 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
590 /* Exit application if required */
592 oldscope = PL_scopestack_ix;
595 /* Warn if there are unjoined threads */
596 S_exit_warning(aTHX);
597 } else if (jmp_rc == 2) {
598 /* Warn handler exited */
599 exit_code = STATUS_CURRENT;
600 while (PL_scopestack_ix > oldscope) {
609 /* At this point, the interpreter may have been freed, so call
610 * free in the the context of of the 'main' interpreter which
611 * can't have been freed due to the veto_cleanup mechanism.
613 aTHX = MY_POOL.main_thread.interp;
615 MUTEX_LOCK(&thread->mutex);
616 S_ithread_free(aTHX_ thread); /* Releases MUTEX */
626 /* Type conversion helper functions */
629 S_ithread_to_SV(pTHX_ SV *obj, ithread *thread, char *classname, bool inc)
635 S_ithread_count_inc(aTHX_ thread);
641 sv = newSVrv(obj, classname);
642 sv_setiv(sv, PTR2IV(thread));
643 mg = sv_magicext(sv, Nullsv, PERL_MAGIC_shared_scalar, &ithread_vtbl, (char *)thread, 0);
644 mg->mg_flags |= MGf_DUP;
651 S_SV_to_ithread(pTHX_ SV *sv)
653 /* Argument is a thread */
655 return (INT2PTR(ithread *, SvIV(SvRV(sv))));
657 /* Argument is classname, therefore return current thread */
658 return (S_ithread_get(aTHX));
663 * Called in context of parent thread.
664 * Called with MY_POOL.create_destruct_mutex locked. (Unlocked on error.)
668 pTHX_ SV *init_function,
675 ithread *current_thread = S_ithread_get(aTHX);
677 SV **tmps_tmp = PL_tmps_stack;
678 IV tmps_ix = PL_tmps_ix;
680 int rc_stack_size = 0;
681 int rc_thread_create = 0;
685 /* Allocate thread structure in context of the main thread's interpreter */
687 PERL_SET_CONTEXT(MY_POOL.main_thread.interp);
688 thread = (ithread *)PerlMemShared_malloc(sizeof(ithread));
690 PERL_SET_CONTEXT(aTHX);
692 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
693 PerlLIO_write(PerlIO_fileno(Perl_error_log), PL_no_mem, strlen(PL_no_mem));
696 Zero(thread, 1, ithread);
698 /* Add to threads list */
699 thread->next = &MY_POOL.main_thread;
700 thread->prev = MY_POOL.main_thread.prev;
701 MY_POOL.main_thread.prev = thread;
702 thread->prev->next = thread;
703 MY_POOL.total_threads++;
705 /* 1 ref to be held by the local var 'thread' in S_ithread_run().
706 * 1 ref to be held by the threads object that we assume we will
707 * be embedded in upon our return.
708 * 1 ref to be the responsibility of join/detach, so we don't get
709 * freed until join/detach, even if no thread objects remain.
710 * This allows the following to work:
711 * { threads->create(sub{...}); } threads->object(1)->join;
715 /* Block new thread until ->create() call finishes */
716 MUTEX_INIT(&thread->mutex);
717 MUTEX_LOCK(&thread->mutex);
719 thread->tid = MY_POOL.tid_counter++;
720 thread->stack_size = S_good_stack_size(aTHX_ stack_size);
721 thread->gimme = gimme;
722 thread->state = exit_opt;
724 /* "Clone" our interpreter into the thread's interpreter.
725 * This gives thread access to "static data" and code.
727 PerlIO_flush((PerlIO *)NULL);
728 S_ithread_set(aTHX_ thread);
730 SAVEBOOL(PL_srand_called); /* Save this so it becomes the correct value */
731 PL_srand_called = FALSE; /* Set it to false so we can detect if it gets
732 set during the clone */
735 /* perl_clone() will leave us the new interpreter's context. This poses
736 * two problems for our signal handler. First, it sets the new context
737 * before the new interpreter struct is fully initialized, so our signal
738 * handler might find bogus data in the interpreter struct it gets.
739 * Second, even if the interpreter is initialized before a signal comes in,
740 * we would like to avoid that interpreter receiving notifications for
741 * signals (especially when they ought to be for the one running in this
742 * thread), until it is running in its own thread. Another problem is that
743 * the new thread will not have set the context until some time after it
744 * has started, so it won't be safe for our signal handler to run until
747 * So we block most signals here, so the new thread will inherit the signal
748 * mask, and unblock them right after the thread creation. The original
749 * mask is saved in the thread struct so that the new thread can restore
752 S_block_most_signals(&thread->initial_sigmask);
756 thread->interp = perl_clone(aTHX, CLONEf_KEEP_PTR_TABLE | CLONEf_CLONE_HOST);
758 thread->interp = perl_clone(aTHX, CLONEf_KEEP_PTR_TABLE);
761 /* perl_clone() leaves us in new interpreter's context. As it is tricky
762 * to spot an implicit aTHX, create a new scope with aTHX matching the
763 * context for the duration of our work for new interpreter.
766 CLONE_PARAMS clone_param;
768 dTHXa(thread->interp);
772 /* Here we remove END blocks since they should only run in the thread
775 SvREFCNT_dec(PL_endav);
778 clone_param.flags = 0;
779 if (SvPOK(init_function)) {
780 thread->init_function = newSV(0);
781 sv_copypv(thread->init_function, init_function);
783 thread->init_function =
784 SvREFCNT_inc(sv_dup(init_function, &clone_param));
787 thread->params = sv_dup(params, &clone_param);
788 SvREFCNT_inc_void(thread->params);
790 /* The code below checks that anything living on the tmps stack and
791 * has been cloned (so it lives in the ptr_table) has a refcount
794 * If the refcount is 0 it means that a something on the stack/context
795 * was holding a reference to it and since we init_stacks() in
796 * perl_clone that won't get cleaned and we will get a leaked scalar.
797 * The reason it was cloned was that it lived on the @_ stack.
799 * Example of this can be found in bugreport 15837 where calls in the
800 * parameter list end up as a temp.
802 * One could argue that this fix should be in perl_clone.
804 while (tmps_ix > 0) {
805 SV* sv = (SV*)ptr_table_fetch(PL_ptr_table, tmps_tmp[tmps_ix]);
807 if (sv && SvREFCNT(sv) == 0) {
808 SvREFCNT_inc_void(sv);
813 SvTEMP_off(thread->init_function);
814 ptr_table_free(PL_ptr_table);
816 PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
818 S_ithread_set(aTHX_ current_thread);
819 PERL_SET_CONTEXT(aTHX);
821 /* Create/start the thread */
823 thread->handle = CreateThread(NULL,
824 (DWORD)thread->stack_size,
827 STACK_SIZE_PARAM_IS_A_RESERVATION,
831 STATIC pthread_attr_t attr;
832 STATIC int attr_inited = 0;
833 STATIC int attr_joinable = PTHREAD_CREATE_JOINABLE;
835 pthread_attr_init(&attr);
839 # ifdef PTHREAD_ATTR_SETDETACHSTATE
840 /* Threads start out joinable */
841 PTHREAD_ATTR_SETDETACHSTATE(&attr, attr_joinable);
844 # ifdef _POSIX_THREAD_ATTR_STACKSIZE
845 /* Set thread's stack size */
846 if (thread->stack_size > 0) {
847 rc_stack_size = pthread_attr_setstacksize(&attr, (size_t)thread->stack_size);
851 /* Create the thread */
852 if (! rc_stack_size) {
853 # ifdef OLD_PTHREADS_API
854 rc_thread_create = pthread_create(&thread->thr,
859 # if defined(HAS_PTHREAD_ATTR_SETSCOPE) && defined(PTHREAD_SCOPE_SYSTEM)
860 pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);
862 rc_thread_create = pthread_create(&thread->thr,
870 /* Now it's safe to accept signals, since we're in our own interpreter's
871 * context and we have created the thread.
873 S_set_sigmask(&thread->initial_sigmask);
876 # ifdef _POSIX_THREAD_ATTR_STACKSIZE
877 /* Try to get thread's actual stack size */
881 stacksize = pthread_attr_getstacksize(attr);
883 if (! pthread_attr_getstacksize(&attr, &stacksize))
886 thread->stack_size = (IV)stacksize;
893 /* Check for errors */
895 if (thread->handle == NULL) {
897 if (rc_stack_size || rc_thread_create) {
899 /* Must unlock mutex for destruct call */
900 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
902 thread->state |= PERL_ITHR_NONVIABLE;
903 S_ithread_free(aTHX_ thread); /* Releases MUTEX */
905 if (ckWARN_d(WARN_THREADS)) {
907 Perl_warn(aTHX_ "Thread creation failed: pthread_attr_setstacksize(%" IVdf ") returned %d", thread->stack_size, rc_stack_size);
909 Perl_warn(aTHX_ "Thread creation failed: pthread_create returned %d", rc_thread_create);
916 MY_POOL.running_threads++;
921 #endif /* USE_ITHREADS */
924 MODULE = threads PACKAGE = threads PREFIX = ithread_
934 SV *function_to_call;
940 SV *thread_exit_only;
946 if ((items >= 2) && SvROK(ST(1)) && SvTYPE(SvRV(ST(1)))==SVt_PVHV) {
948 Perl_croak(aTHX_ "Usage: threads->create(\\%%specs, function, ...)");
950 specs = (HV*)SvRV(ST(1));
954 Perl_croak(aTHX_ "Usage: threads->create(function, ...)");
960 if (sv_isobject(ST(0))) {
962 classname = HvNAME(SvSTASH(SvRV(ST(0))));
963 thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
964 MUTEX_LOCK(&thread->mutex);
965 stack_size = thread->stack_size;
966 exit_opt = thread->state & PERL_ITHR_THREAD_EXIT_ONLY;
967 MUTEX_UNLOCK(&thread->mutex);
969 /* threads->create() */
970 classname = (char *)SvPV_nolen(ST(0));
971 stack_size = MY_POOL.default_stack_size;
972 thread_exit_only = get_sv("threads::thread_exit_only", GV_ADD);
973 exit_opt = (SvTRUE(thread_exit_only))
974 ? PERL_ITHR_THREAD_EXIT_ONLY : 0;
977 function_to_call = ST(idx+1);
982 if (hv_exists(specs, "stack", 5)) {
983 stack_size = SvIV(*hv_fetch(specs, "stack", 5, 0));
984 } else if (hv_exists(specs, "stacksize", 9)) {
985 stack_size = SvIV(*hv_fetch(specs, "stacksize", 9, 0));
986 } else if (hv_exists(specs, "stack_size", 10)) {
987 stack_size = SvIV(*hv_fetch(specs, "stack_size", 10, 0));
991 if (hv_exists(specs, "context", 7)) {
992 str = (char *)SvPV_nolen(*hv_fetch(specs, "context", 7, 0));
1009 Perl_croak(aTHX_ "Invalid context: %s", str);
1011 } else if (hv_exists(specs, "array", 5)) {
1012 if (SvTRUE(*hv_fetch(specs, "array", 5, 0))) {
1015 } else if (hv_exists(specs, "list", 4)) {
1016 if (SvTRUE(*hv_fetch(specs, "list", 4, 0))) {
1019 } else if (hv_exists(specs, "scalar", 6)) {
1020 if (SvTRUE(*hv_fetch(specs, "scalar", 6, 0))) {
1023 } else if (hv_exists(specs, "void", 4)) {
1024 if (SvTRUE(*hv_fetch(specs, "void", 4, 0))) {
1029 /* exit => thread_only */
1030 if (hv_exists(specs, "exit", 4)) {
1031 str = (char *)SvPV_nolen(*hv_fetch(specs, "exit", 4, 0));
1032 exit_opt = (*str == 't' || *str == 'T')
1033 ? PERL_ITHR_THREAD_EXIT_ONLY : 0;
1036 if (context == -1) {
1037 context = GIMME_V; /* Implicit context */
1039 context |= (GIMME_V & (~(G_ARRAY|G_SCALAR|G_VOID)));
1045 for (ii=2; ii < items ; ii++) {
1046 av_push(params, SvREFCNT_inc(ST(idx+ii)));
1051 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
1052 thread = S_ithread_create(aTHX_ function_to_call,
1056 newRV_noinc((SV*)params));
1058 XSRETURN_UNDEF; /* Mutex already unlocked */
1060 ST(0) = sv_2mortal(S_ithread_to_SV(aTHX_ Nullsv, thread, classname, FALSE));
1061 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
1063 /* Let thread run */
1064 MUTEX_UNLOCK(&thread->mutex);
1066 /* XSRETURN(1); - implied */
1076 int want_running = 0;
1080 /* Class method only */
1082 Perl_croak(aTHX_ "Usage: threads->list(...)");
1084 classname = (char *)SvPV_nolen(ST(0));
1086 /* Calling context */
1087 list_context = (GIMME_V == G_ARRAY);
1089 /* Running or joinable parameter */
1091 want_running = SvTRUE(ST(1));
1094 /* Walk through threads list */
1095 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
1096 for (thread = MY_POOL.main_thread.next;
1097 thread != &MY_POOL.main_thread;
1098 thread = thread->next)
1100 MUTEX_LOCK(&thread->mutex);
1101 state = thread->state;
1102 MUTEX_UNLOCK(&thread->mutex);
1104 /* Ignore detached or joined threads */
1105 if (state & PERL_ITHR_UNCALLABLE) {
1109 /* Filter per parameter */
1112 if (state & PERL_ITHR_FINISHED) {
1113 continue; /* Not running */
1116 if (! (state & PERL_ITHR_FINISHED)) {
1117 continue; /* Still running - not joinable yet */
1122 /* Push object on stack if list context */
1124 XPUSHs(sv_2mortal(S_ithread_to_SV(aTHX_ Nullsv, thread, classname, TRUE)));
1128 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
1129 /* If scalar context, send back count */
1130 if (! list_context) {
1141 /* Class method only */
1142 if ((items != 1) || SvROK(ST(0))) {
1143 Perl_croak(aTHX_ "Usage: threads->self()");
1145 classname = (char *)SvPV_nolen(ST(0));
1147 thread = S_ithread_get(aTHX);
1149 ST(0) = sv_2mortal(S_ithread_to_SV(aTHX_ Nullsv, thread, classname, TRUE));
1150 /* XSRETURN(1); - implied */
1158 PERL_UNUSED_VAR(items);
1159 thread = S_SV_to_ithread(aTHX_ ST(0));
1160 XST_mUV(0, thread->tid);
1161 /* XSRETURN(1); - implied */
1168 ithread *current_thread;
1179 /* Object method only */
1180 if ((items != 1) || ! sv_isobject(ST(0))) {
1181 Perl_croak(aTHX_ "Usage: $thr->join()");
1184 /* Check if the thread is joinable and not ourselves */
1185 thread = S_SV_to_ithread(aTHX_ ST(0));
1186 current_thread = S_ithread_get(aTHX);
1188 MUTEX_LOCK(&thread->mutex);
1189 if ((join_err = (thread->state & PERL_ITHR_UNCALLABLE))) {
1190 MUTEX_UNLOCK(&thread->mutex);
1191 Perl_croak(aTHX_ (join_err & PERL_ITHR_DETACHED)
1192 ? "Cannot join a detached thread"
1193 : "Thread already joined");
1194 } else if (thread->tid == current_thread->tid) {
1195 MUTEX_UNLOCK(&thread->mutex);
1196 Perl_croak(aTHX_ "Cannot join self");
1199 /* Mark as joined */
1200 thread->state |= PERL_ITHR_JOINED;
1201 MUTEX_UNLOCK(&thread->mutex);
1203 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
1204 MY_POOL.joinable_threads--;
1205 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
1207 /* Join the thread */
1209 if (WaitForSingleObject(thread->handle, INFINITE) != WAIT_OBJECT_0) {
1210 /* Timeout/abandonment unexpected here; check $^E */
1211 Perl_croak(aTHX_ "PANIC: underlying join failed");
1214 if ((rc_join = pthread_join(thread->thr, &retval)) != 0) {
1215 /* In progress/deadlock/unknown unexpected here; check $! */
1217 Perl_croak(aTHX_ "PANIC: underlying join failed");
1221 MUTEX_LOCK(&thread->mutex);
1222 /* Get the return value from the call_sv */
1223 /* Objects do not survive this process - FIXME */
1224 if ((thread->gimme & G_WANT) != G_VOID) {
1226 PerlInterpreter *other_perl;
1227 CLONE_PARAMS clone_params;
1229 params_copy = (AV *)SvRV(thread->params);
1230 other_perl = thread->interp;
1231 clone_params.stashes = newAV();
1232 clone_params.flags = CLONEf_JOIN_IN;
1233 PL_ptr_table = ptr_table_new();
1234 S_ithread_set(aTHX_ thread);
1235 /* Ensure 'meaningful' addresses retain their meaning */
1236 ptr_table_store(PL_ptr_table, &other_perl->Isv_undef, &PL_sv_undef);
1237 ptr_table_store(PL_ptr_table, &other_perl->Isv_no, &PL_sv_no);
1238 ptr_table_store(PL_ptr_table, &other_perl->Isv_yes, &PL_sv_yes);
1239 params = (AV *)sv_dup((SV*)params_copy, &clone_params);
1240 S_ithread_set(aTHX_ current_thread);
1241 SvREFCNT_dec(clone_params.stashes);
1242 SvREFCNT_inc_void(params);
1243 ptr_table_free(PL_ptr_table);
1244 PL_ptr_table = NULL;
1247 /* If thread didn't die, then we can free its interpreter */
1248 if (! (thread->state & PERL_ITHR_DIED)) {
1249 S_ithread_clear(aTHX_ thread);
1251 S_ithread_free(aTHX_ thread); /* Releases MUTEX */
1253 /* If no return values, then just return */
1258 /* Put return values on stack */
1259 len = (int)AvFILL(params);
1260 for (ii=0; ii <= len; ii++) {
1261 SV* param = av_shift(params);
1262 XPUSHs(sv_2mortal(param));
1265 /* Free return value array */
1266 SvREFCNT_dec(params);
1272 PERL_UNUSED_VAR(items);
1283 PERL_UNUSED_VAR(items);
1285 /* Detach the thread */
1286 thread = S_SV_to_ithread(aTHX_ ST(0));
1287 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
1288 MUTEX_LOCK(&thread->mutex);
1289 if (! (detach_err = (thread->state & PERL_ITHR_UNCALLABLE))) {
1290 /* Thread is detachable */
1291 thread->state |= PERL_ITHR_DETACHED;
1293 /* Windows has no 'detach thread' function */
1295 PERL_THREAD_DETACH(thread->thr);
1297 if (thread->state & PERL_ITHR_FINISHED) {
1298 MY_POOL.joinable_threads--;
1300 MY_POOL.running_threads--;
1301 MY_POOL.detached_threads++;
1304 MUTEX_UNLOCK(&thread->mutex);
1305 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
1308 Perl_croak(aTHX_ (detach_err & PERL_ITHR_DETACHED)
1309 ? "Thread already detached"
1310 : "Cannot detach a joined thread");
1313 /* If thread is finished and didn't die,
1314 * then we can free its interpreter */
1315 MUTEX_LOCK(&thread->mutex);
1316 if ((thread->state & PERL_ITHR_FINISHED) &&
1317 ! (thread->state & PERL_ITHR_DIED))
1319 S_ithread_clear(aTHX_ thread);
1321 S_ithread_free(aTHX_ thread); /* Releases MUTEX */
1331 /* Must have safe signals */
1332 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG) {
1333 Perl_croak(aTHX_ "Cannot signal threads without safe signals");
1336 /* Object method only */
1337 if ((items != 2) || ! sv_isobject(ST(0))) {
1338 Perl_croak(aTHX_ "Usage: $thr->kill('SIG...')");
1342 sig_name = SvPV_nolen(ST(1));
1343 if (isALPHA(*sig_name)) {
1344 if (*sig_name == 'S' && sig_name[1] == 'I' && sig_name[2] == 'G') {
1347 if ((signal = whichsig(sig_name)) < 0) {
1348 Perl_croak(aTHX_ "Unrecognized signal name: %s", sig_name);
1351 signal = SvIV(ST(1));
1354 /* Set the signal for the thread */
1355 thread = S_SV_to_ithread(aTHX_ ST(0));
1356 MUTEX_LOCK(&thread->mutex);
1357 if (thread->interp) {
1358 dTHXa(thread->interp);
1359 PL_psig_pend[signal]++;
1362 MUTEX_UNLOCK(&thread->mutex);
1364 /* Return the thread to allow for method chaining */
1366 /* XSRETURN(1); - implied */
1370 ithread_DESTROY(...)
1372 PERL_UNUSED_VAR(items);
1373 sv_unmagic(SvRV(ST(0)), PERL_MAGIC_shared_scalar);
1381 PERL_UNUSED_VAR(items);
1383 /* Compares TIDs to determine thread equality */
1384 if (sv_isobject(ST(0)) && sv_isobject(ST(1))) {
1385 ithread *thr1 = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1386 ithread *thr2 = INT2PTR(ithread *, SvIV(SvRV(ST(1))));
1387 are_equal = (thr1->tid == thr2->tid);
1392 /* Return 0 on false for backward compatibility */
1395 /* XSRETURN(1); - implied */
1408 /* Class method only */
1410 Perl_croak(aTHX_ "Usage: threads->object($tid)");
1412 classname = (char *)SvPV_nolen(ST(0));
1414 if ((items < 2) || ! SvOK(ST(1))) {
1418 /* threads->object($tid) */
1421 /* Walk through threads list */
1422 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
1423 for (thread = MY_POOL.main_thread.next;
1424 thread != &MY_POOL.main_thread;
1425 thread = thread->next)
1428 if (thread->tid == tid) {
1429 /* Ignore if detached or joined */
1430 MUTEX_LOCK(&thread->mutex);
1431 state = thread->state;
1432 MUTEX_UNLOCK(&thread->mutex);
1433 if (! (state & PERL_ITHR_UNCALLABLE)) {
1434 /* Put object on stack */
1435 ST(0) = sv_2mortal(S_ithread_to_SV(aTHX_ Nullsv, thread, classname, TRUE));
1441 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
1446 /* XSRETURN(1); - implied */
1450 ithread__handle(...);
1454 PERL_UNUSED_VAR(items);
1455 thread = S_SV_to_ithread(aTHX_ ST(0));
1457 XST_mUV(0, PTR2UV(&thread->handle));
1459 XST_mUV(0, PTR2UV(&thread->thr));
1461 /* XSRETURN(1); - implied */
1465 ithread_get_stack_size(...)
1470 PERL_UNUSED_VAR(items);
1471 if (sv_isobject(ST(0))) {
1472 /* $thr->get_stack_size() */
1473 ithread *thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1474 stack_size = thread->stack_size;
1476 /* threads->get_stack_size() */
1477 stack_size = MY_POOL.default_stack_size;
1479 XST_mIV(0, stack_size);
1480 /* XSRETURN(1); - implied */
1484 ithread_set_stack_size(...)
1490 Perl_croak(aTHX_ "Usage: threads->set_stack_size($size)");
1492 if (sv_isobject(ST(0))) {
1493 Perl_croak(aTHX_ "Cannot change stack size of an existing thread");
1495 if (! looks_like_number(ST(1))) {
1496 Perl_croak(aTHX_ "Stack size must be numeric");
1499 old_size = MY_POOL.default_stack_size;
1500 MY_POOL.default_stack_size = S_good_stack_size(aTHX_ SvIV(ST(1)));
1501 XST_mIV(0, old_size);
1502 /* XSRETURN(1); - implied */
1506 ithread_is_running(...)
1510 /* Object method only */
1511 if ((items != 1) || ! sv_isobject(ST(0))) {
1512 Perl_croak(aTHX_ "Usage: $thr->is_running()");
1515 thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1516 MUTEX_LOCK(&thread->mutex);
1517 ST(0) = (thread->state & PERL_ITHR_FINISHED) ? &PL_sv_no : &PL_sv_yes;
1518 MUTEX_UNLOCK(&thread->mutex);
1519 /* XSRETURN(1); - implied */
1523 ithread_is_detached(...)
1527 PERL_UNUSED_VAR(items);
1528 thread = S_SV_to_ithread(aTHX_ ST(0));
1529 MUTEX_LOCK(&thread->mutex);
1530 ST(0) = (thread->state & PERL_ITHR_DETACHED) ? &PL_sv_yes : &PL_sv_no;
1531 MUTEX_UNLOCK(&thread->mutex);
1532 /* XSRETURN(1); - implied */
1536 ithread_is_joinable(...)
1540 /* Object method only */
1541 if ((items != 1) || ! sv_isobject(ST(0))) {
1542 Perl_croak(aTHX_ "Usage: $thr->is_joinable()");
1545 thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1546 MUTEX_LOCK(&thread->mutex);
1547 ST(0) = ((thread->state & PERL_ITHR_FINISHED) &&
1548 ! (thread->state & PERL_ITHR_UNCALLABLE))
1549 ? &PL_sv_yes : &PL_sv_no;
1550 MUTEX_UNLOCK(&thread->mutex);
1551 /* XSRETURN(1); - implied */
1555 ithread_wantarray(...)
1559 PERL_UNUSED_VAR(items);
1560 thread = S_SV_to_ithread(aTHX_ ST(0));
1561 ST(0) = ((thread->gimme & G_WANT) == G_ARRAY) ? &PL_sv_yes :
1562 ((thread->gimme & G_WANT) == G_VOID) ? &PL_sv_undef
1563 /* G_SCALAR */ : &PL_sv_no;
1564 /* XSRETURN(1); - implied */
1568 ithread_set_thread_exit_only(...)
1573 Perl_croak(aTHX_ "Usage: ->set_thread_exit_only(boolean)");
1575 thread = S_SV_to_ithread(aTHX_ ST(0));
1576 MUTEX_LOCK(&thread->mutex);
1577 if (SvTRUE(ST(1))) {
1578 thread->state |= PERL_ITHR_THREAD_EXIT_ONLY;
1580 thread->state &= ~PERL_ITHR_THREAD_EXIT_ONLY;
1582 MUTEX_UNLOCK(&thread->mutex);
1591 /* Object method only */
1592 if ((items != 1) || ! sv_isobject(ST(0))) {
1593 Perl_croak(aTHX_ "Usage: $thr->err()");
1596 thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1597 MUTEX_LOCK(&thread->mutex);
1599 /* If thread died, then clone the error into the calling thread */
1600 if (thread->state & PERL_ITHR_DIED) {
1601 PerlInterpreter *other_perl;
1602 CLONE_PARAMS clone_params;
1603 ithread *current_thread;
1605 other_perl = thread->interp;
1606 clone_params.stashes = newAV();
1607 clone_params.flags = CLONEf_JOIN_IN;
1608 PL_ptr_table = ptr_table_new();
1609 current_thread = S_ithread_get(aTHX);
1610 S_ithread_set(aTHX_ thread);
1611 /* Ensure 'meaningful' addresses retain their meaning */
1612 ptr_table_store(PL_ptr_table, &other_perl->Isv_undef, &PL_sv_undef);
1613 ptr_table_store(PL_ptr_table, &other_perl->Isv_no, &PL_sv_no);
1614 ptr_table_store(PL_ptr_table, &other_perl->Isv_yes, &PL_sv_yes);
1615 err = sv_dup(thread->err, &clone_params);
1616 S_ithread_set(aTHX_ current_thread);
1617 SvREFCNT_dec(clone_params.stashes);
1618 SvREFCNT_inc_void(err);
1619 /* If error was an object, bless it into the correct class */
1620 if (thread->err_class) {
1621 sv_bless(err, gv_stashpv(thread->err_class, 1));
1623 ptr_table_free(PL_ptr_table);
1624 PL_ptr_table = NULL;
1627 MUTEX_UNLOCK(&thread->mutex);
1633 ST(0) = sv_2mortal(err);
1634 /* XSRETURN(1); - implied */
1637 #endif /* USE_ITHREADS */
1643 SV *my_pool_sv = *hv_fetch(PL_modglobal, MY_POOL_KEY,
1644 sizeof(MY_POOL_KEY)-1, TRUE);
1645 my_pool_t *my_poolp = (my_pool_t*)SvPVX(newSV(sizeof(my_pool_t)-1));
1649 Zero(my_poolp, 1, my_pool_t);
1650 sv_setuv(my_pool_sv, PTR2UV(my_poolp));
1652 PL_perl_destruct_level = 2;
1653 MUTEX_INIT(&MY_POOL.create_destruct_mutex);
1654 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
1656 PL_threadhook = &Perl_ithread_hook;
1658 MY_POOL.tid_counter = 1;
1659 # ifdef THREAD_CREATE_NEEDS_STACK
1660 MY_POOL.default_stack_size = THREAD_CREATE_NEEDS_STACK;
1663 /* The 'main' thread is thread 0.
1664 * It is detached (unjoinable) and immortal.
1667 MUTEX_INIT(&MY_POOL.main_thread.mutex);
1669 /* Head of the threads list */
1670 MY_POOL.main_thread.next = &MY_POOL.main_thread;
1671 MY_POOL.main_thread.prev = &MY_POOL.main_thread;
1673 MY_POOL.main_thread.count = 1; /* Immortal */
1675 MY_POOL.main_thread.interp = aTHX;
1676 MY_POOL.main_thread.state = PERL_ITHR_DETACHED; /* Detached */
1677 MY_POOL.main_thread.stack_size = MY_POOL.default_stack_size;
1679 MY_POOL.main_thread.thr = GetCurrentThreadId();
1681 MY_POOL.main_thread.thr = pthread_self();
1684 S_ithread_set(aTHX_ &MY_POOL.main_thread);
1685 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
1686 #endif /* USE_ITHREADS */