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 */
78 sigset_t initial_sigmask; /* Thread wakes up with signals blocked */
82 #define MY_CXT_KEY "threads::_cxt" XS_VERSION
85 /* Used by Perl interpreter for thread context switching */
92 #define MY_POOL_KEY "threads::_pool" XS_VERSION
95 /* Structure for 'main' thread
96 * Also forms the 'base' for the doubly-linked list of threads */
99 /* Protects the creation and destruction of threads*/
100 perl_mutex create_destruct_mutex;
107 IV default_stack_size;
112 SV *my_pool_sv = *hv_fetch(PL_modglobal, MY_POOL_KEY, \
113 sizeof(MY_POOL_KEY)-1, TRUE); \
114 my_pool_t *my_poolp = INT2PTR(my_pool_t*, SvUV(my_pool_sv))
116 #define MY_POOL (*my_poolp)
118 /* Block most signals for calling thread, setting the old signal mask to
119 * oldmask, if it is not NULL */
121 S_block_most_signals(sigset_t *oldmask)
125 sigfillset(&newmask);
126 /* Don't block certain "important" signals (stolen from mg.c) */
128 sigdelset(&newmask, SIGILL);
131 sigdelset(&newmask, SIGBUS);
134 sigdelset(&newmask, SIGSEGV);
138 /* XXX: How to do this on win32? */
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 /* XXX: How to do this on win32? */
156 return sigprocmask(SIG_SETMASK, newmask, NULL);
158 return pthread_sigmask(SIG_SETMASK, newmask, NULL);
162 /* Used by Perl interpreter for thread context switching */
164 S_ithread_set(pTHX_ ithread *thread)
167 MY_CXT.context = thread;
174 return (MY_CXT.context);
178 /* Free any data (such as the Perl interpreter) attached to an ithread
179 * structure. This is a bit like undef on SVs, where the SV isn't freed,
180 * but the PVX is. Must be called with thread->mutex already locked. Also,
181 * must be called with MY_POOL.create_destruct_mutex unlocked as destruction
182 * of the interpreter can lead to recursive destruction calls that could
183 * lead to a deadlock on that mutex.
186 S_ithread_clear(pTHX_ ithread *thread)
188 PerlInterpreter *interp;
191 assert(((thread->state & PERL_ITHR_FINISHED) &&
192 (thread->state & PERL_ITHR_UNCALLABLE))
194 (thread->state & PERL_ITHR_NONVIABLE));
196 /* We temporarily set the interpreter context to the interpreter being
197 * destroyed. It's in no condition to handle signals while it's being
200 S_block_most_signals(&origmask);
202 interp = thread->interp;
206 PERL_SET_CONTEXT(interp);
207 S_ithread_set(aTHX_ thread);
209 SvREFCNT_dec(thread->params);
210 thread->params = Nullsv;
213 SvREFCNT_dec(thread->err);
214 thread->err = Nullsv;
217 perl_destruct(interp);
219 thread->interp = NULL;
222 PERL_SET_CONTEXT(aTHX);
223 S_set_sigmask(&origmask);
227 /* Decrement the refcount of an ithread, and if it reaches zero, free it.
228 * Must be called with the mutex held.
229 * On return, mutex is released (or destroyed).
232 S_ithread_free(pTHX_ ithread *thread)
239 if (! (thread->state & PERL_ITHR_NONVIABLE)) {
240 assert(thread->count > 0);
241 if (--thread->count > 0) {
242 MUTEX_UNLOCK(&thread->mutex);
245 assert((thread->state & PERL_ITHR_FINISHED) &&
246 (thread->state & PERL_ITHR_UNCALLABLE));
248 MUTEX_UNLOCK(&thread->mutex);
250 /* Main thread (0) is immortal and should never get here */
251 assert(thread->tid != 0);
253 /* Remove from circular list of threads */
254 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
255 assert(thread->prev && thread->next);
256 thread->next->prev = thread->prev;
257 thread->prev->next = thread->next;
260 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
262 /* Thread is now disowned */
263 MUTEX_LOCK(&thread->mutex);
264 S_ithread_clear(aTHX_ thread);
267 handle = thread->handle;
268 thread->handle = NULL;
270 MUTEX_UNLOCK(&thread->mutex);
271 MUTEX_DESTROY(&thread->mutex);
279 PerlMemShared_free(thread);
281 /* total_threads >= 1 is used to veto cleanup by the main thread,
282 * should it happen to exit while other threads still exist.
283 * Decrement this as the very last thing in the thread's existence.
284 * Otherwise, MY_POOL and global state such as PL_op_mutex may get
285 * freed while we're still using it.
287 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
288 MY_POOL.total_threads--;
289 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
294 S_ithread_count_inc(pTHX_ ithread *thread)
296 MUTEX_LOCK(&thread->mutex);
298 MUTEX_UNLOCK(&thread->mutex);
302 /* Warn if exiting with any unjoined threads */
306 int veto_cleanup, warn;
309 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
310 veto_cleanup = (MY_POOL.total_threads > 0);
311 warn = (MY_POOL.running_threads || MY_POOL.joinable_threads);
312 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
315 if (ckWARN_d(WARN_THREADS)) {
316 Perl_warn(aTHX_ "Perl exited with active threads:\n\t%"
317 IVdf " running and unjoined\n\t%"
318 IVdf " finished and unjoined\n\t%"
319 IVdf " running and detached\n",
320 MY_POOL.running_threads,
321 MY_POOL.joinable_threads,
322 MY_POOL.detached_threads);
326 return (veto_cleanup);
330 /* Called from perl_destruct() in each thread. If it's the main thread,
331 * stop it from freeing everything if there are other threads still running.
334 Perl_ithread_hook(pTHX)
337 return ((aTHX == MY_POOL.main_thread.interp) ? S_exit_warning(aTHX) : 0);
341 /* MAGIC (in mg.h sense) hooks */
344 ithread_mg_get(pTHX_ SV *sv, MAGIC *mg)
346 ithread *thread = (ithread *)mg->mg_ptr;
347 SvIV_set(sv, PTR2IV(thread));
353 ithread_mg_free(pTHX_ SV *sv, MAGIC *mg)
355 ithread *thread = (ithread *)mg->mg_ptr;
356 MUTEX_LOCK(&thread->mutex);
357 S_ithread_free(aTHX_ thread); /* Releases MUTEX */
362 ithread_mg_dup(pTHX_ MAGIC *mg, CLONE_PARAMS *param)
364 S_ithread_count_inc(aTHX_ (ithread *)mg->mg_ptr);
368 MGVTBL ithread_vtbl = {
369 ithread_mg_get, /* get */
373 ithread_mg_free, /* free */
375 ithread_mg_dup /* dup */
379 /* Provided default, minimum and rational stack sizes */
381 S_good_stack_size(pTHX_ IV stack_size)
385 /* Use default stack size if no stack size specified */
387 return (MY_POOL.default_stack_size);
390 #ifdef PTHREAD_STACK_MIN
391 /* Can't use less than minimum */
392 if (stack_size < PTHREAD_STACK_MIN) {
393 if (ckWARN(WARN_THREADS)) {
394 Perl_warn(aTHX_ "Using minimum thread stack size of %" IVdf, (IV)PTHREAD_STACK_MIN);
396 return (PTHREAD_STACK_MIN);
400 /* Round up to page size boundary */
401 if (MY_POOL.page_size <= 0) {
402 #if defined(HAS_SYSCONF) && (defined(_SC_PAGESIZE) || defined(_SC_MMAP_PAGE_SIZE))
403 SETERRNO(0, SS_NORMAL);
405 MY_POOL.page_size = sysconf(_SC_PAGESIZE);
407 MY_POOL.page_size = sysconf(_SC_MMAP_PAGE_SIZE);
409 if ((long)MY_POOL.page_size < 0) {
411 SV * const error = get_sv("@", 0);
412 (void)SvUPGRADE(error, SVt_PV);
413 Perl_croak(aTHX_ "PANIC: sysconf: %s", SvPV_nolen(error));
415 Perl_croak(aTHX_ "PANIC: sysconf: pagesize unknown");
419 # ifdef HAS_GETPAGESIZE
420 MY_POOL.page_size = getpagesize();
422 # if defined(I_SYS_PARAM) && defined(PAGESIZE)
423 MY_POOL.page_size = PAGESIZE;
425 MY_POOL.page_size = 8192; /* A conservative default */
428 if (MY_POOL.page_size <= 0) {
429 Perl_croak(aTHX_ "PANIC: bad pagesize %" IVdf, (IV)MY_POOL.page_size);
433 stack_size = ((stack_size + (MY_POOL.page_size - 1)) / MY_POOL.page_size) * MY_POOL.page_size;
439 /* Starts executing the thread.
440 * Passed as the C level function to run in the new thread.
443 STATIC THREAD_RET_TYPE
444 S_ithread_run(LPVOID arg)
447 S_ithread_run(void * arg)
450 ithread *thread = (ithread *)arg;
453 int exit_app = 0; /* Thread terminated using 'exit' */
455 int died = 0; /* Thread terminated abnormally */
459 dTHXa(thread->interp);
463 /* Blocked until ->create() call finishes */
464 MUTEX_LOCK(&thread->mutex);
465 MUTEX_UNLOCK(&thread->mutex);
467 PERL_SET_CONTEXT(thread->interp);
468 S_ithread_set(aTHX_ thread);
470 /* Thread starts with most signals blocked - restore the signal mask from
471 * the ithread struct.
473 S_set_sigmask(&thread->initial_sigmask);
475 PL_perl_destruct_level = 2;
478 AV *params = (AV *)SvRV(thread->params);
479 int len = (int)av_len(params)+1;
486 /* Put args on the stack */
488 for (ii=0; ii < len; ii++) {
489 XPUSHs(av_shift(params));
493 oldscope = PL_scopestack_ix;
496 /* Run the specified function */
497 len = (int)call_sv(thread->init_function, thread->gimme|G_EVAL);
498 } else if (jmp_rc == 2) {
501 exit_code = STATUS_CURRENT;
502 while (PL_scopestack_ix > oldscope) {
508 /* The interpreter is finished, so this thread can stop receiving
509 * signals. This way, our signal handler doesn't get called in the
510 * middle of our parent thread calling perl_destruct()...
512 S_block_most_signals(NULL);
514 /* Remove args from stack and put back in params array */
516 for (ii=len-1; ii >= 0; ii--) {
518 if (jmp_rc == 0 && (thread->gimme & G_WANT) != G_VOID) {
519 av_store(params, ii, SvREFCNT_inc(sv));
526 /* Check for abnormal termination */
528 died = PERL_ITHR_DIED;
529 thread->err = newSVsv(ERRSV);
530 /* If ERRSV is an object, remember the classname and then
531 * rebless into 'main' so it will survive 'cloning'
533 if (sv_isobject(thread->err)) {
534 thread->err_class = HvNAME(SvSTASH(SvRV(thread->err)));
535 sv_bless(thread->err, gv_stashpv("main", 0));
538 if (ckWARN_d(WARN_THREADS)) {
539 oldscope = PL_scopestack_ix;
542 /* Warn that thread died */
543 Perl_warn(aTHX_ "Thread %" UVuf " terminated abnormally: %" SVf, thread->tid, ERRSV);
544 } else if (jmp_rc == 2) {
545 /* Warn handler exited */
547 exit_code = STATUS_CURRENT;
548 while (PL_scopestack_ix > oldscope) {
556 /* Release function ref */
557 SvREFCNT_dec(thread->init_function);
558 thread->init_function = Nullsv;
561 PerlIO_flush((PerlIO *)NULL);
563 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
564 MUTEX_LOCK(&thread->mutex);
565 /* Mark as finished */
566 thread->state |= (PERL_ITHR_FINISHED | died);
567 /* Clear exit flag if required */
568 if (thread->state & PERL_ITHR_THREAD_EXIT_ONLY) {
572 /* Adjust thread status counts */
573 if (thread->state & PERL_ITHR_DETACHED) {
574 MY_POOL.detached_threads--;
576 MY_POOL.running_threads--;
577 MY_POOL.joinable_threads++;
579 MUTEX_UNLOCK(&thread->mutex);
580 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
582 /* Exit application if required */
584 oldscope = PL_scopestack_ix;
587 /* Warn if there are unjoined threads */
588 S_exit_warning(aTHX);
589 } else if (jmp_rc == 2) {
590 /* Warn handler exited */
591 exit_code = STATUS_CURRENT;
592 while (PL_scopestack_ix > oldscope) {
601 /* At this point, the interpreter may have been freed, so call
602 * free in the the context of of the 'main' interpreter which
603 * can't have been freed due to the veto_cleanup mechanism.
605 aTHX = MY_POOL.main_thread.interp;
607 MUTEX_LOCK(&thread->mutex);
608 S_ithread_free(aTHX_ thread); /* Releases MUTEX */
618 /* Type conversion helper functions */
621 S_ithread_to_SV(pTHX_ SV *obj, ithread *thread, char *classname, bool inc)
627 S_ithread_count_inc(aTHX_ thread);
633 sv = newSVrv(obj, classname);
634 sv_setiv(sv, PTR2IV(thread));
635 mg = sv_magicext(sv, Nullsv, PERL_MAGIC_shared_scalar, &ithread_vtbl, (char *)thread, 0);
636 mg->mg_flags |= MGf_DUP;
643 S_SV_to_ithread(pTHX_ SV *sv)
645 /* Argument is a thread */
647 return (INT2PTR(ithread *, SvIV(SvRV(sv))));
649 /* Argument is classname, therefore return current thread */
650 return (S_ithread_get(aTHX));
655 * Called in context of parent thread.
656 * Called with MY_POOL.create_destruct_mutex locked. (Unlocked on error.)
660 pTHX_ SV *init_function,
667 ithread *current_thread = S_ithread_get(aTHX);
669 SV **tmps_tmp = PL_tmps_stack;
670 IV tmps_ix = PL_tmps_ix;
672 int rc_stack_size = 0;
673 int rc_thread_create = 0;
677 /* Allocate thread structure in context of the main thread's interpreter */
679 PERL_SET_CONTEXT(MY_POOL.main_thread.interp);
680 thread = (ithread *)PerlMemShared_malloc(sizeof(ithread));
682 PERL_SET_CONTEXT(aTHX);
684 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
685 PerlLIO_write(PerlIO_fileno(Perl_error_log), PL_no_mem, strlen(PL_no_mem));
688 Zero(thread, 1, ithread);
690 /* Add to threads list */
691 thread->next = &MY_POOL.main_thread;
692 thread->prev = MY_POOL.main_thread.prev;
693 MY_POOL.main_thread.prev = thread;
694 thread->prev->next = thread;
695 MY_POOL.total_threads++;
697 /* 1 ref to be held by the local var 'thread' in S_ithread_run().
698 * 1 ref to be held by the threads object that we assume we will
699 * be embedded in upon our return.
700 * 1 ref to be the responsibility of join/detach, so we don't get
701 * freed until join/detach, even if no thread objects remain.
702 * This allows the following to work:
703 * { threads->create(sub{...}); } threads->object(1)->join;
707 /* Block new thread until ->create() call finishes */
708 MUTEX_INIT(&thread->mutex);
709 MUTEX_LOCK(&thread->mutex);
711 thread->tid = MY_POOL.tid_counter++;
712 thread->stack_size = S_good_stack_size(aTHX_ stack_size);
713 thread->gimme = gimme;
714 thread->state = exit_opt;
716 /* "Clone" our interpreter into the thread's interpreter.
717 * This gives thread access to "static data" and code.
719 PerlIO_flush((PerlIO *)NULL);
720 S_ithread_set(aTHX_ thread);
722 SAVEBOOL(PL_srand_called); /* Save this so it becomes the correct value */
723 PL_srand_called = FALSE; /* Set it to false so we can detect if it gets
724 set during the clone */
726 /* perl_clone() will leave us the new interpreter's context. This poses
727 * two problems for our signal handler. First, it sets the new context
728 * before the new interpreter struct is fully initialized, so our signal
729 * handler might find bogus data in the interpreter struct it gets.
730 * Second, even if the interpreter is initialized before a signal comes in,
731 * we would like to avoid that interpreter receiving notifications for
732 * signals (especially when they ought to be for the one running in this
733 * thread), until it is running in its own thread. Another problem is that
734 * the new thread will not have set the context until some time after it
735 * has started, so it won't be safe for our signal handler to run until
738 * So we block most signals here, so the new thread will inherit the signal
739 * mask, and unblock them right after the thread creation. The original
740 * mask is saved in the thread struct so that the new thread can restore
743 S_block_most_signals(&thread->initial_sigmask);
746 thread->interp = perl_clone(aTHX, CLONEf_KEEP_PTR_TABLE | CLONEf_CLONE_HOST);
748 thread->interp = perl_clone(aTHX, CLONEf_KEEP_PTR_TABLE);
751 /* perl_clone() leaves us in new interpreter's context. As it is tricky
752 * to spot an implicit aTHX, create a new scope with aTHX matching the
753 * context for the duration of our work for new interpreter.
756 CLONE_PARAMS clone_param;
758 dTHXa(thread->interp);
762 /* Here we remove END blocks since they should only run in the thread
765 SvREFCNT_dec(PL_endav);
768 clone_param.flags = 0;
769 if (SvPOK(init_function)) {
770 thread->init_function = newSV(0);
771 sv_copypv(thread->init_function, init_function);
773 thread->init_function =
774 SvREFCNT_inc(sv_dup(init_function, &clone_param));
777 thread->params = sv_dup(params, &clone_param);
778 SvREFCNT_inc_void(thread->params);
780 /* The code below checks that anything living on the tmps stack and
781 * has been cloned (so it lives in the ptr_table) has a refcount
784 * If the refcount is 0 it means that a something on the stack/context
785 * was holding a reference to it and since we init_stacks() in
786 * perl_clone that won't get cleaned and we will get a leaked scalar.
787 * The reason it was cloned was that it lived on the @_ stack.
789 * Example of this can be found in bugreport 15837 where calls in the
790 * parameter list end up as a temp.
792 * One could argue that this fix should be in perl_clone.
794 while (tmps_ix > 0) {
795 SV* sv = (SV*)ptr_table_fetch(PL_ptr_table, tmps_tmp[tmps_ix]);
797 if (sv && SvREFCNT(sv) == 0) {
798 SvREFCNT_inc_void(sv);
803 SvTEMP_off(thread->init_function);
804 ptr_table_free(PL_ptr_table);
806 PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
808 S_ithread_set(aTHX_ current_thread);
809 PERL_SET_CONTEXT(aTHX);
811 /* Create/start the thread */
813 thread->handle = CreateThread(NULL,
814 (DWORD)thread->stack_size,
817 STACK_SIZE_PARAM_IS_A_RESERVATION,
821 STATIC pthread_attr_t attr;
822 STATIC int attr_inited = 0;
823 STATIC int attr_joinable = PTHREAD_CREATE_JOINABLE;
825 pthread_attr_init(&attr);
829 # ifdef PTHREAD_ATTR_SETDETACHSTATE
830 /* Threads start out joinable */
831 PTHREAD_ATTR_SETDETACHSTATE(&attr, attr_joinable);
834 # ifdef _POSIX_THREAD_ATTR_STACKSIZE
835 /* Set thread's stack size */
836 if (thread->stack_size > 0) {
837 rc_stack_size = pthread_attr_setstacksize(&attr, (size_t)thread->stack_size);
841 /* Create the thread */
842 if (! rc_stack_size) {
843 # ifdef OLD_PTHREADS_API
844 rc_thread_create = pthread_create(&thread->thr,
849 # if defined(HAS_PTHREAD_ATTR_SETSCOPE) && defined(PTHREAD_SCOPE_SYSTEM)
850 pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);
852 rc_thread_create = pthread_create(&thread->thr,
859 /* Now it's safe to accept signals, since we're in our own interpreter's
860 * context and we have created the thread.
862 S_set_sigmask(&thread->initial_sigmask);
864 # ifdef _POSIX_THREAD_ATTR_STACKSIZE
865 /* Try to get thread's actual stack size */
869 stacksize = pthread_attr_getstacksize(attr);
871 if (! pthread_attr_getstacksize(&attr, &stacksize))
874 thread->stack_size = (IV)stacksize;
881 /* Check for errors */
883 if (thread->handle == NULL) {
885 if (rc_stack_size || rc_thread_create) {
887 /* Must unlock mutex for destruct call */
888 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
890 thread->state |= PERL_ITHR_NONVIABLE;
891 S_ithread_free(aTHX_ thread); /* Releases MUTEX */
893 if (ckWARN_d(WARN_THREADS)) {
895 Perl_warn(aTHX_ "Thread creation failed: pthread_attr_setstacksize(%" IVdf ") returned %d", thread->stack_size, rc_stack_size);
897 Perl_warn(aTHX_ "Thread creation failed: pthread_create returned %d", rc_thread_create);
904 MY_POOL.running_threads++;
909 #endif /* USE_ITHREADS */
912 MODULE = threads PACKAGE = threads PREFIX = ithread_
922 SV *function_to_call;
928 SV *thread_exit_only;
934 if ((items >= 2) && SvROK(ST(1)) && SvTYPE(SvRV(ST(1)))==SVt_PVHV) {
936 Perl_croak(aTHX_ "Usage: threads->create(\\%%specs, function, ...)");
938 specs = (HV*)SvRV(ST(1));
942 Perl_croak(aTHX_ "Usage: threads->create(function, ...)");
948 if (sv_isobject(ST(0))) {
950 classname = HvNAME(SvSTASH(SvRV(ST(0))));
951 thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
952 MUTEX_LOCK(&thread->mutex);
953 stack_size = thread->stack_size;
954 exit_opt = thread->state & PERL_ITHR_THREAD_EXIT_ONLY;
955 MUTEX_UNLOCK(&thread->mutex);
957 /* threads->create() */
958 classname = (char *)SvPV_nolen(ST(0));
959 stack_size = MY_POOL.default_stack_size;
960 thread_exit_only = get_sv("threads::thread_exit_only", GV_ADD);
961 exit_opt = (SvTRUE(thread_exit_only))
962 ? PERL_ITHR_THREAD_EXIT_ONLY : 0;
965 function_to_call = ST(idx+1);
970 if (hv_exists(specs, "stack", 5)) {
971 stack_size = SvIV(*hv_fetch(specs, "stack", 5, 0));
972 } else if (hv_exists(specs, "stacksize", 9)) {
973 stack_size = SvIV(*hv_fetch(specs, "stacksize", 9, 0));
974 } else if (hv_exists(specs, "stack_size", 10)) {
975 stack_size = SvIV(*hv_fetch(specs, "stack_size", 10, 0));
979 if (hv_exists(specs, "context", 7)) {
980 str = (char *)SvPV_nolen(*hv_fetch(specs, "context", 7, 0));
997 Perl_croak(aTHX_ "Invalid context: %s", str);
999 } else if (hv_exists(specs, "array", 5)) {
1000 if (SvTRUE(*hv_fetch(specs, "array", 5, 0))) {
1003 } else if (hv_exists(specs, "list", 4)) {
1004 if (SvTRUE(*hv_fetch(specs, "list", 4, 0))) {
1007 } else if (hv_exists(specs, "scalar", 6)) {
1008 if (SvTRUE(*hv_fetch(specs, "scalar", 6, 0))) {
1011 } else if (hv_exists(specs, "void", 4)) {
1012 if (SvTRUE(*hv_fetch(specs, "void", 4, 0))) {
1017 /* exit => thread_only */
1018 if (hv_exists(specs, "exit", 4)) {
1019 str = (char *)SvPV_nolen(*hv_fetch(specs, "exit", 4, 0));
1020 exit_opt = (*str == 't' || *str == 'T')
1021 ? PERL_ITHR_THREAD_EXIT_ONLY : 0;
1024 if (context == -1) {
1025 context = GIMME_V; /* Implicit context */
1027 context |= (GIMME_V & (~(G_ARRAY|G_SCALAR|G_VOID)));
1033 for (ii=2; ii < items ; ii++) {
1034 av_push(params, SvREFCNT_inc(ST(idx+ii)));
1039 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
1040 thread = S_ithread_create(aTHX_ function_to_call,
1044 newRV_noinc((SV*)params));
1046 XSRETURN_UNDEF; /* Mutex already unlocked */
1048 ST(0) = sv_2mortal(S_ithread_to_SV(aTHX_ Nullsv, thread, classname, FALSE));
1049 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
1051 /* Let thread run */
1052 MUTEX_UNLOCK(&thread->mutex);
1054 /* XSRETURN(1); - implied */
1064 int want_running = 0;
1068 /* Class method only */
1070 Perl_croak(aTHX_ "Usage: threads->list(...)");
1072 classname = (char *)SvPV_nolen(ST(0));
1074 /* Calling context */
1075 list_context = (GIMME_V == G_ARRAY);
1077 /* Running or joinable parameter */
1079 want_running = SvTRUE(ST(1));
1082 /* Walk through threads list */
1083 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
1084 for (thread = MY_POOL.main_thread.next;
1085 thread != &MY_POOL.main_thread;
1086 thread = thread->next)
1088 MUTEX_LOCK(&thread->mutex);
1089 state = thread->state;
1090 MUTEX_UNLOCK(&thread->mutex);
1092 /* Ignore detached or joined threads */
1093 if (state & PERL_ITHR_UNCALLABLE) {
1097 /* Filter per parameter */
1100 if (state & PERL_ITHR_FINISHED) {
1101 continue; /* Not running */
1104 if (! (state & PERL_ITHR_FINISHED)) {
1105 continue; /* Still running - not joinable yet */
1110 /* Push object on stack if list context */
1112 XPUSHs(sv_2mortal(S_ithread_to_SV(aTHX_ Nullsv, thread, classname, TRUE)));
1116 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
1117 /* If scalar context, send back count */
1118 if (! list_context) {
1129 /* Class method only */
1130 if ((items != 1) || SvROK(ST(0))) {
1131 Perl_croak(aTHX_ "Usage: threads->self()");
1133 classname = (char *)SvPV_nolen(ST(0));
1135 thread = S_ithread_get(aTHX);
1137 ST(0) = sv_2mortal(S_ithread_to_SV(aTHX_ Nullsv, thread, classname, TRUE));
1138 /* XSRETURN(1); - implied */
1146 PERL_UNUSED_VAR(items);
1147 thread = S_SV_to_ithread(aTHX_ ST(0));
1148 XST_mUV(0, thread->tid);
1149 /* XSRETURN(1); - implied */
1156 ithread *current_thread;
1167 /* Object method only */
1168 if ((items != 1) || ! sv_isobject(ST(0))) {
1169 Perl_croak(aTHX_ "Usage: $thr->join()");
1172 /* Check if the thread is joinable and not ourselves */
1173 thread = S_SV_to_ithread(aTHX_ ST(0));
1174 current_thread = S_ithread_get(aTHX);
1176 MUTEX_LOCK(&thread->mutex);
1177 if ((join_err = (thread->state & PERL_ITHR_UNCALLABLE))) {
1178 MUTEX_UNLOCK(&thread->mutex);
1179 Perl_croak(aTHX_ (join_err & PERL_ITHR_DETACHED)
1180 ? "Cannot join a detached thread"
1181 : "Thread already joined");
1182 } else if (thread->tid == current_thread->tid) {
1183 MUTEX_UNLOCK(&thread->mutex);
1184 Perl_croak(aTHX_ "Cannot join self");
1187 /* Mark as joined */
1188 thread->state |= PERL_ITHR_JOINED;
1189 MUTEX_UNLOCK(&thread->mutex);
1191 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
1192 MY_POOL.joinable_threads--;
1193 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
1195 /* Join the thread */
1197 if (WaitForSingleObject(thread->handle, INFINITE) != WAIT_OBJECT_0) {
1198 /* Timeout/abandonment unexpected here; check $^E */
1199 Perl_croak(aTHX_ "PANIC: underlying join failed");
1202 if ((rc_join = pthread_join(thread->thr, &retval)) != 0) {
1203 /* In progress/deadlock/unknown unexpected here; check $! */
1205 Perl_croak(aTHX_ "PANIC: underlying join failed");
1209 MUTEX_LOCK(&thread->mutex);
1210 /* Get the return value from the call_sv */
1211 /* Objects do not survive this process - FIXME */
1212 if ((thread->gimme & G_WANT) != G_VOID) {
1214 PerlInterpreter *other_perl;
1215 CLONE_PARAMS clone_params;
1217 params_copy = (AV *)SvRV(thread->params);
1218 other_perl = thread->interp;
1219 clone_params.stashes = newAV();
1220 clone_params.flags = CLONEf_JOIN_IN;
1221 PL_ptr_table = ptr_table_new();
1222 S_ithread_set(aTHX_ thread);
1223 /* Ensure 'meaningful' addresses retain their meaning */
1224 ptr_table_store(PL_ptr_table, &other_perl->Isv_undef, &PL_sv_undef);
1225 ptr_table_store(PL_ptr_table, &other_perl->Isv_no, &PL_sv_no);
1226 ptr_table_store(PL_ptr_table, &other_perl->Isv_yes, &PL_sv_yes);
1227 params = (AV *)sv_dup((SV*)params_copy, &clone_params);
1228 S_ithread_set(aTHX_ current_thread);
1229 SvREFCNT_dec(clone_params.stashes);
1230 SvREFCNT_inc_void(params);
1231 ptr_table_free(PL_ptr_table);
1232 PL_ptr_table = NULL;
1235 /* If thread didn't die, then we can free its interpreter */
1236 if (! (thread->state & PERL_ITHR_DIED)) {
1237 S_ithread_clear(aTHX_ thread);
1239 S_ithread_free(aTHX_ thread); /* Releases MUTEX */
1241 /* If no return values, then just return */
1246 /* Put return values on stack */
1247 len = (int)AvFILL(params);
1248 for (ii=0; ii <= len; ii++) {
1249 SV* param = av_shift(params);
1250 XPUSHs(sv_2mortal(param));
1253 /* Free return value array */
1254 SvREFCNT_dec(params);
1260 PERL_UNUSED_VAR(items);
1271 PERL_UNUSED_VAR(items);
1273 /* Detach the thread */
1274 thread = S_SV_to_ithread(aTHX_ ST(0));
1275 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
1276 MUTEX_LOCK(&thread->mutex);
1277 if (! (detach_err = (thread->state & PERL_ITHR_UNCALLABLE))) {
1278 /* Thread is detachable */
1279 thread->state |= PERL_ITHR_DETACHED;
1281 /* Windows has no 'detach thread' function */
1283 PERL_THREAD_DETACH(thread->thr);
1285 if (thread->state & PERL_ITHR_FINISHED) {
1286 MY_POOL.joinable_threads--;
1288 MY_POOL.running_threads--;
1289 MY_POOL.detached_threads++;
1292 MUTEX_UNLOCK(&thread->mutex);
1293 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
1296 Perl_croak(aTHX_ (detach_err & PERL_ITHR_DETACHED)
1297 ? "Thread already detached"
1298 : "Cannot detach a joined thread");
1301 /* If thread is finished and didn't die,
1302 * then we can free its interpreter */
1303 MUTEX_LOCK(&thread->mutex);
1304 if ((thread->state & PERL_ITHR_FINISHED) &&
1305 ! (thread->state & PERL_ITHR_DIED))
1307 S_ithread_clear(aTHX_ thread);
1309 S_ithread_free(aTHX_ thread); /* Releases MUTEX */
1319 /* Must have safe signals */
1320 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG) {
1321 Perl_croak(aTHX_ "Cannot signal threads without safe signals");
1324 /* Object method only */
1325 if ((items != 2) || ! sv_isobject(ST(0))) {
1326 Perl_croak(aTHX_ "Usage: $thr->kill('SIG...')");
1330 sig_name = SvPV_nolen(ST(1));
1331 if (isALPHA(*sig_name)) {
1332 if (*sig_name == 'S' && sig_name[1] == 'I' && sig_name[2] == 'G') {
1335 if ((signal = whichsig(sig_name)) < 0) {
1336 Perl_croak(aTHX_ "Unrecognized signal name: %s", sig_name);
1339 signal = SvIV(ST(1));
1342 /* Set the signal for the thread */
1343 thread = S_SV_to_ithread(aTHX_ ST(0));
1344 MUTEX_LOCK(&thread->mutex);
1345 if (thread->interp) {
1346 dTHXa(thread->interp);
1347 PL_psig_pend[signal]++;
1350 MUTEX_UNLOCK(&thread->mutex);
1352 /* Return the thread to allow for method chaining */
1354 /* XSRETURN(1); - implied */
1358 ithread_DESTROY(...)
1360 PERL_UNUSED_VAR(items);
1361 sv_unmagic(SvRV(ST(0)), PERL_MAGIC_shared_scalar);
1369 PERL_UNUSED_VAR(items);
1371 /* Compares TIDs to determine thread equality */
1372 if (sv_isobject(ST(0)) && sv_isobject(ST(1))) {
1373 ithread *thr1 = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1374 ithread *thr2 = INT2PTR(ithread *, SvIV(SvRV(ST(1))));
1375 are_equal = (thr1->tid == thr2->tid);
1380 /* Return 0 on false for backward compatibility */
1383 /* XSRETURN(1); - implied */
1396 /* Class method only */
1398 Perl_croak(aTHX_ "Usage: threads->object($tid)");
1400 classname = (char *)SvPV_nolen(ST(0));
1402 if ((items < 2) || ! SvOK(ST(1))) {
1406 /* threads->object($tid) */
1409 /* Walk through threads list */
1410 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
1411 for (thread = MY_POOL.main_thread.next;
1412 thread != &MY_POOL.main_thread;
1413 thread = thread->next)
1416 if (thread->tid == tid) {
1417 /* Ignore if detached or joined */
1418 MUTEX_LOCK(&thread->mutex);
1419 state = thread->state;
1420 MUTEX_UNLOCK(&thread->mutex);
1421 if (! (state & PERL_ITHR_UNCALLABLE)) {
1422 /* Put object on stack */
1423 ST(0) = sv_2mortal(S_ithread_to_SV(aTHX_ Nullsv, thread, classname, TRUE));
1429 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
1434 /* XSRETURN(1); - implied */
1438 ithread__handle(...);
1442 PERL_UNUSED_VAR(items);
1443 thread = S_SV_to_ithread(aTHX_ ST(0));
1445 XST_mUV(0, PTR2UV(&thread->handle));
1447 XST_mUV(0, PTR2UV(&thread->thr));
1449 /* XSRETURN(1); - implied */
1453 ithread_get_stack_size(...)
1458 PERL_UNUSED_VAR(items);
1459 if (sv_isobject(ST(0))) {
1460 /* $thr->get_stack_size() */
1461 ithread *thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1462 stack_size = thread->stack_size;
1464 /* threads->get_stack_size() */
1465 stack_size = MY_POOL.default_stack_size;
1467 XST_mIV(0, stack_size);
1468 /* XSRETURN(1); - implied */
1472 ithread_set_stack_size(...)
1478 Perl_croak(aTHX_ "Usage: threads->set_stack_size($size)");
1480 if (sv_isobject(ST(0))) {
1481 Perl_croak(aTHX_ "Cannot change stack size of an existing thread");
1483 if (! looks_like_number(ST(1))) {
1484 Perl_croak(aTHX_ "Stack size must be numeric");
1487 old_size = MY_POOL.default_stack_size;
1488 MY_POOL.default_stack_size = S_good_stack_size(aTHX_ SvIV(ST(1)));
1489 XST_mIV(0, old_size);
1490 /* XSRETURN(1); - implied */
1494 ithread_is_running(...)
1498 /* Object method only */
1499 if ((items != 1) || ! sv_isobject(ST(0))) {
1500 Perl_croak(aTHX_ "Usage: $thr->is_running()");
1503 thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1504 MUTEX_LOCK(&thread->mutex);
1505 ST(0) = (thread->state & PERL_ITHR_FINISHED) ? &PL_sv_no : &PL_sv_yes;
1506 MUTEX_UNLOCK(&thread->mutex);
1507 /* XSRETURN(1); - implied */
1511 ithread_is_detached(...)
1515 PERL_UNUSED_VAR(items);
1516 thread = S_SV_to_ithread(aTHX_ ST(0));
1517 MUTEX_LOCK(&thread->mutex);
1518 ST(0) = (thread->state & PERL_ITHR_DETACHED) ? &PL_sv_yes : &PL_sv_no;
1519 MUTEX_UNLOCK(&thread->mutex);
1520 /* XSRETURN(1); - implied */
1524 ithread_is_joinable(...)
1528 /* Object method only */
1529 if ((items != 1) || ! sv_isobject(ST(0))) {
1530 Perl_croak(aTHX_ "Usage: $thr->is_joinable()");
1533 thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1534 MUTEX_LOCK(&thread->mutex);
1535 ST(0) = ((thread->state & PERL_ITHR_FINISHED) &&
1536 ! (thread->state & PERL_ITHR_UNCALLABLE))
1537 ? &PL_sv_yes : &PL_sv_no;
1538 MUTEX_UNLOCK(&thread->mutex);
1539 /* XSRETURN(1); - implied */
1543 ithread_wantarray(...)
1547 PERL_UNUSED_VAR(items);
1548 thread = S_SV_to_ithread(aTHX_ ST(0));
1549 ST(0) = ((thread->gimme & G_WANT) == G_ARRAY) ? &PL_sv_yes :
1550 ((thread->gimme & G_WANT) == G_VOID) ? &PL_sv_undef
1551 /* G_SCALAR */ : &PL_sv_no;
1552 /* XSRETURN(1); - implied */
1556 ithread_set_thread_exit_only(...)
1561 Perl_croak(aTHX_ "Usage: ->set_thread_exit_only(boolean)");
1563 thread = S_SV_to_ithread(aTHX_ ST(0));
1564 MUTEX_LOCK(&thread->mutex);
1565 if (SvTRUE(ST(1))) {
1566 thread->state |= PERL_ITHR_THREAD_EXIT_ONLY;
1568 thread->state &= ~PERL_ITHR_THREAD_EXIT_ONLY;
1570 MUTEX_UNLOCK(&thread->mutex);
1579 /* Object method only */
1580 if ((items != 1) || ! sv_isobject(ST(0))) {
1581 Perl_croak(aTHX_ "Usage: $thr->err()");
1584 thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1585 MUTEX_LOCK(&thread->mutex);
1587 /* If thread died, then clone the error into the calling thread */
1588 if (thread->state & PERL_ITHR_DIED) {
1589 PerlInterpreter *other_perl;
1590 CLONE_PARAMS clone_params;
1591 ithread *current_thread;
1593 other_perl = thread->interp;
1594 clone_params.stashes = newAV();
1595 clone_params.flags = CLONEf_JOIN_IN;
1596 PL_ptr_table = ptr_table_new();
1597 current_thread = S_ithread_get(aTHX);
1598 S_ithread_set(aTHX_ thread);
1599 /* Ensure 'meaningful' addresses retain their meaning */
1600 ptr_table_store(PL_ptr_table, &other_perl->Isv_undef, &PL_sv_undef);
1601 ptr_table_store(PL_ptr_table, &other_perl->Isv_no, &PL_sv_no);
1602 ptr_table_store(PL_ptr_table, &other_perl->Isv_yes, &PL_sv_yes);
1603 err = sv_dup(thread->err, &clone_params);
1604 S_ithread_set(aTHX_ current_thread);
1605 SvREFCNT_dec(clone_params.stashes);
1606 SvREFCNT_inc_void(err);
1607 /* If error was an object, bless it into the correct class */
1608 if (thread->err_class) {
1609 sv_bless(err, gv_stashpv(thread->err_class, 1));
1611 ptr_table_free(PL_ptr_table);
1612 PL_ptr_table = NULL;
1615 MUTEX_UNLOCK(&thread->mutex);
1621 ST(0) = sv_2mortal(err);
1622 /* XSRETURN(1); - implied */
1625 #endif /* USE_ITHREADS */
1631 SV *my_pool_sv = *hv_fetch(PL_modglobal, MY_POOL_KEY,
1632 sizeof(MY_POOL_KEY)-1, TRUE);
1633 my_pool_t *my_poolp = (my_pool_t*)SvPVX(newSV(sizeof(my_pool_t)-1));
1637 Zero(my_poolp, 1, my_pool_t);
1638 sv_setuv(my_pool_sv, PTR2UV(my_poolp));
1640 PL_perl_destruct_level = 2;
1641 MUTEX_INIT(&MY_POOL.create_destruct_mutex);
1642 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
1644 PL_threadhook = &Perl_ithread_hook;
1646 MY_POOL.tid_counter = 1;
1647 # ifdef THREAD_CREATE_NEEDS_STACK
1648 MY_POOL.default_stack_size = THREAD_CREATE_NEEDS_STACK;
1651 /* The 'main' thread is thread 0.
1652 * It is detached (unjoinable) and immortal.
1655 MUTEX_INIT(&MY_POOL.main_thread.mutex);
1657 /* Head of the threads list */
1658 MY_POOL.main_thread.next = &MY_POOL.main_thread;
1659 MY_POOL.main_thread.prev = &MY_POOL.main_thread;
1661 MY_POOL.main_thread.count = 1; /* Immortal */
1663 MY_POOL.main_thread.interp = aTHX;
1664 MY_POOL.main_thread.state = PERL_ITHR_DETACHED; /* Detached */
1665 MY_POOL.main_thread.stack_size = MY_POOL.default_stack_size;
1667 MY_POOL.main_thread.thr = GetCurrentThreadId();
1669 MY_POOL.main_thread.thr = pthread_self();
1672 S_ithread_set(aTHX_ &MY_POOL.main_thread);
1673 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
1674 #endif /* USE_ITHREADS */