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;
189 assert(((thread->state & PERL_ITHR_FINISHED) &&
190 (thread->state & PERL_ITHR_UNCALLABLE))
192 (thread->state & PERL_ITHR_NONVIABLE));
195 /* We temporarily set the interpreter context to the interpreter being
196 * destroyed. It's in no condition to handle signals while it's being
199 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);
224 S_set_sigmask(&origmask);
229 /* Decrement the refcount of an ithread, and if it reaches zero, free it.
230 * Must be called with the mutex held.
231 * On return, mutex is released (or destroyed).
234 S_ithread_free(pTHX_ ithread *thread)
241 if (! (thread->state & PERL_ITHR_NONVIABLE)) {
242 assert(thread->count > 0);
243 if (--thread->count > 0) {
244 MUTEX_UNLOCK(&thread->mutex);
247 assert((thread->state & PERL_ITHR_FINISHED) &&
248 (thread->state & PERL_ITHR_UNCALLABLE));
250 MUTEX_UNLOCK(&thread->mutex);
252 /* Main thread (0) is immortal and should never get here */
253 assert(thread->tid != 0);
255 /* Remove from circular list of threads */
256 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
257 assert(thread->prev && thread->next);
258 thread->next->prev = thread->prev;
259 thread->prev->next = thread->next;
262 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
264 /* Thread is now disowned */
265 MUTEX_LOCK(&thread->mutex);
266 S_ithread_clear(aTHX_ thread);
269 handle = thread->handle;
270 thread->handle = NULL;
272 MUTEX_UNLOCK(&thread->mutex);
273 MUTEX_DESTROY(&thread->mutex);
281 PerlMemShared_free(thread);
283 /* total_threads >= 1 is used to veto cleanup by the main thread,
284 * should it happen to exit while other threads still exist.
285 * Decrement this as the very last thing in the thread's existence.
286 * Otherwise, MY_POOL and global state such as PL_op_mutex may get
287 * freed while we're still using it.
289 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
290 MY_POOL.total_threads--;
291 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
296 S_ithread_count_inc(pTHX_ ithread *thread)
298 MUTEX_LOCK(&thread->mutex);
300 MUTEX_UNLOCK(&thread->mutex);
304 /* Warn if exiting with any unjoined threads */
308 int veto_cleanup, warn;
311 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
312 veto_cleanup = (MY_POOL.total_threads > 0);
313 warn = (MY_POOL.running_threads || MY_POOL.joinable_threads);
314 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
317 if (ckWARN_d(WARN_THREADS)) {
318 Perl_warn(aTHX_ "Perl exited with active threads:\n\t%"
319 IVdf " running and unjoined\n\t%"
320 IVdf " finished and unjoined\n\t%"
321 IVdf " running and detached\n",
322 MY_POOL.running_threads,
323 MY_POOL.joinable_threads,
324 MY_POOL.detached_threads);
328 return (veto_cleanup);
332 /* Called from perl_destruct() in each thread. If it's the main thread,
333 * stop it from freeing everything if there are other threads still running.
336 Perl_ithread_hook(pTHX)
339 return ((aTHX == MY_POOL.main_thread.interp) ? S_exit_warning(aTHX) : 0);
343 /* MAGIC (in mg.h sense) hooks */
346 ithread_mg_get(pTHX_ SV *sv, MAGIC *mg)
348 ithread *thread = (ithread *)mg->mg_ptr;
349 SvIV_set(sv, PTR2IV(thread));
355 ithread_mg_free(pTHX_ SV *sv, MAGIC *mg)
357 ithread *thread = (ithread *)mg->mg_ptr;
358 MUTEX_LOCK(&thread->mutex);
359 S_ithread_free(aTHX_ thread); /* Releases MUTEX */
364 ithread_mg_dup(pTHX_ MAGIC *mg, CLONE_PARAMS *param)
366 S_ithread_count_inc(aTHX_ (ithread *)mg->mg_ptr);
370 MGVTBL ithread_vtbl = {
371 ithread_mg_get, /* get */
375 ithread_mg_free, /* free */
377 ithread_mg_dup /* dup */
381 /* Provided default, minimum and rational stack sizes */
383 S_good_stack_size(pTHX_ IV stack_size)
387 /* Use default stack size if no stack size specified */
389 return (MY_POOL.default_stack_size);
392 #ifdef PTHREAD_STACK_MIN
393 /* Can't use less than minimum */
394 if (stack_size < PTHREAD_STACK_MIN) {
395 if (ckWARN(WARN_THREADS)) {
396 Perl_warn(aTHX_ "Using minimum thread stack size of %" IVdf, (IV)PTHREAD_STACK_MIN);
398 return (PTHREAD_STACK_MIN);
402 /* Round up to page size boundary */
403 if (MY_POOL.page_size <= 0) {
404 #if defined(HAS_SYSCONF) && (defined(_SC_PAGESIZE) || defined(_SC_MMAP_PAGE_SIZE))
405 SETERRNO(0, SS_NORMAL);
407 MY_POOL.page_size = sysconf(_SC_PAGESIZE);
409 MY_POOL.page_size = sysconf(_SC_MMAP_PAGE_SIZE);
411 if ((long)MY_POOL.page_size < 0) {
413 SV * const error = get_sv("@", 0);
414 (void)SvUPGRADE(error, SVt_PV);
415 Perl_croak(aTHX_ "PANIC: sysconf: %s", SvPV_nolen(error));
417 Perl_croak(aTHX_ "PANIC: sysconf: pagesize unknown");
421 # ifdef HAS_GETPAGESIZE
422 MY_POOL.page_size = getpagesize();
424 # if defined(I_SYS_PARAM) && defined(PAGESIZE)
425 MY_POOL.page_size = PAGESIZE;
427 MY_POOL.page_size = 8192; /* A conservative default */
430 if (MY_POOL.page_size <= 0) {
431 Perl_croak(aTHX_ "PANIC: bad pagesize %" IVdf, (IV)MY_POOL.page_size);
435 stack_size = ((stack_size + (MY_POOL.page_size - 1)) / MY_POOL.page_size) * MY_POOL.page_size;
441 /* Starts executing the thread.
442 * Passed as the C level function to run in the new thread.
445 STATIC THREAD_RET_TYPE
446 S_ithread_run(LPVOID arg)
449 S_ithread_run(void * arg)
452 ithread *thread = (ithread *)arg;
455 int exit_app = 0; /* Thread terminated using 'exit' */
457 int died = 0; /* Thread terminated abnormally */
461 dTHXa(thread->interp);
465 /* Blocked until ->create() call finishes */
466 MUTEX_LOCK(&thread->mutex);
467 MUTEX_UNLOCK(&thread->mutex);
469 PERL_SET_CONTEXT(thread->interp);
470 S_ithread_set(aTHX_ thread);
473 /* Thread starts with most signals blocked - restore the signal mask from
474 * the ithread struct.
476 S_set_sigmask(&thread->initial_sigmask);
479 PL_perl_destruct_level = 2;
482 AV *params = (AV *)SvRV(thread->params);
483 int len = (int)av_len(params)+1;
490 /* Put args on the stack */
492 for (ii=0; ii < len; ii++) {
493 XPUSHs(av_shift(params));
497 oldscope = PL_scopestack_ix;
500 /* Run the specified function */
501 len = (int)call_sv(thread->init_function, thread->gimme|G_EVAL);
502 } else if (jmp_rc == 2) {
505 exit_code = STATUS_CURRENT;
506 while (PL_scopestack_ix > oldscope) {
513 /* The interpreter is finished, so this thread can stop receiving
514 * signals. This way, our signal handler doesn't get called in the
515 * middle of our parent thread calling perl_destruct()...
517 S_block_most_signals(NULL);
520 /* Remove args from stack and put back in params array */
522 for (ii=len-1; ii >= 0; ii--) {
524 if (jmp_rc == 0 && (thread->gimme & G_WANT) != G_VOID) {
525 av_store(params, ii, SvREFCNT_inc(sv));
532 /* Check for abnormal termination */
534 died = PERL_ITHR_DIED;
535 thread->err = newSVsv(ERRSV);
536 /* If ERRSV is an object, remember the classname and then
537 * rebless into 'main' so it will survive 'cloning'
539 if (sv_isobject(thread->err)) {
540 thread->err_class = HvNAME(SvSTASH(SvRV(thread->err)));
541 sv_bless(thread->err, gv_stashpv("main", 0));
544 if (ckWARN_d(WARN_THREADS)) {
545 oldscope = PL_scopestack_ix;
548 /* Warn that thread died */
549 Perl_warn(aTHX_ "Thread %" UVuf " terminated abnormally: %" SVf, thread->tid, ERRSV);
550 } else if (jmp_rc == 2) {
551 /* Warn handler exited */
553 exit_code = STATUS_CURRENT;
554 while (PL_scopestack_ix > oldscope) {
562 /* Release function ref */
563 SvREFCNT_dec(thread->init_function);
564 thread->init_function = Nullsv;
567 PerlIO_flush((PerlIO *)NULL);
569 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
570 MUTEX_LOCK(&thread->mutex);
571 /* Mark as finished */
572 thread->state |= (PERL_ITHR_FINISHED | died);
573 /* Clear exit flag if required */
574 if (thread->state & PERL_ITHR_THREAD_EXIT_ONLY) {
578 /* Adjust thread status counts */
579 if (thread->state & PERL_ITHR_DETACHED) {
580 MY_POOL.detached_threads--;
582 MY_POOL.running_threads--;
583 MY_POOL.joinable_threads++;
585 MUTEX_UNLOCK(&thread->mutex);
586 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
588 /* Exit application if required */
590 oldscope = PL_scopestack_ix;
593 /* Warn if there are unjoined threads */
594 S_exit_warning(aTHX);
595 } else if (jmp_rc == 2) {
596 /* Warn handler exited */
597 exit_code = STATUS_CURRENT;
598 while (PL_scopestack_ix > oldscope) {
607 /* At this point, the interpreter may have been freed, so call
608 * free in the the context of of the 'main' interpreter which
609 * can't have been freed due to the veto_cleanup mechanism.
611 aTHX = MY_POOL.main_thread.interp;
613 MUTEX_LOCK(&thread->mutex);
614 S_ithread_free(aTHX_ thread); /* Releases MUTEX */
624 /* Type conversion helper functions */
627 S_ithread_to_SV(pTHX_ SV *obj, ithread *thread, char *classname, bool inc)
633 S_ithread_count_inc(aTHX_ thread);
639 sv = newSVrv(obj, classname);
640 sv_setiv(sv, PTR2IV(thread));
641 mg = sv_magicext(sv, Nullsv, PERL_MAGIC_shared_scalar, &ithread_vtbl, (char *)thread, 0);
642 mg->mg_flags |= MGf_DUP;
649 S_SV_to_ithread(pTHX_ SV *sv)
651 /* Argument is a thread */
653 return (INT2PTR(ithread *, SvIV(SvRV(sv))));
655 /* Argument is classname, therefore return current thread */
656 return (S_ithread_get(aTHX));
661 * Called in context of parent thread.
662 * Called with MY_POOL.create_destruct_mutex locked. (Unlocked on error.)
666 pTHX_ SV *init_function,
673 ithread *current_thread = S_ithread_get(aTHX);
675 SV **tmps_tmp = PL_tmps_stack;
676 IV tmps_ix = PL_tmps_ix;
678 int rc_stack_size = 0;
679 int rc_thread_create = 0;
683 /* Allocate thread structure in context of the main thread's interpreter */
685 PERL_SET_CONTEXT(MY_POOL.main_thread.interp);
686 thread = (ithread *)PerlMemShared_malloc(sizeof(ithread));
688 PERL_SET_CONTEXT(aTHX);
690 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
691 PerlLIO_write(PerlIO_fileno(Perl_error_log), PL_no_mem, strlen(PL_no_mem));
694 Zero(thread, 1, ithread);
696 /* Add to threads list */
697 thread->next = &MY_POOL.main_thread;
698 thread->prev = MY_POOL.main_thread.prev;
699 MY_POOL.main_thread.prev = thread;
700 thread->prev->next = thread;
701 MY_POOL.total_threads++;
703 /* 1 ref to be held by the local var 'thread' in S_ithread_run().
704 * 1 ref to be held by the threads object that we assume we will
705 * be embedded in upon our return.
706 * 1 ref to be the responsibility of join/detach, so we don't get
707 * freed until join/detach, even if no thread objects remain.
708 * This allows the following to work:
709 * { threads->create(sub{...}); } threads->object(1)->join;
713 /* Block new thread until ->create() call finishes */
714 MUTEX_INIT(&thread->mutex);
715 MUTEX_LOCK(&thread->mutex);
717 thread->tid = MY_POOL.tid_counter++;
718 thread->stack_size = S_good_stack_size(aTHX_ stack_size);
719 thread->gimme = gimme;
720 thread->state = exit_opt;
722 /* "Clone" our interpreter into the thread's interpreter.
723 * This gives thread access to "static data" and code.
725 PerlIO_flush((PerlIO *)NULL);
726 S_ithread_set(aTHX_ thread);
728 SAVEBOOL(PL_srand_called); /* Save this so it becomes the correct value */
729 PL_srand_called = FALSE; /* Set it to false so we can detect if it gets
730 set during the clone */
733 /* perl_clone() will leave us the new interpreter's context. This poses
734 * two problems for our signal handler. First, it sets the new context
735 * before the new interpreter struct is fully initialized, so our signal
736 * handler might find bogus data in the interpreter struct it gets.
737 * Second, even if the interpreter is initialized before a signal comes in,
738 * we would like to avoid that interpreter receiving notifications for
739 * signals (especially when they ought to be for the one running in this
740 * thread), until it is running in its own thread. Another problem is that
741 * the new thread will not have set the context until some time after it
742 * has started, so it won't be safe for our signal handler to run until
745 * So we block most signals here, so the new thread will inherit the signal
746 * mask, and unblock them right after the thread creation. The original
747 * mask is saved in the thread struct so that the new thread can restore
750 S_block_most_signals(&thread->initial_sigmask);
754 thread->interp = perl_clone(aTHX, CLONEf_KEEP_PTR_TABLE | CLONEf_CLONE_HOST);
756 thread->interp = perl_clone(aTHX, CLONEf_KEEP_PTR_TABLE);
759 /* perl_clone() leaves us in new interpreter's context. As it is tricky
760 * to spot an implicit aTHX, create a new scope with aTHX matching the
761 * context for the duration of our work for new interpreter.
764 CLONE_PARAMS clone_param;
766 dTHXa(thread->interp);
770 /* Here we remove END blocks since they should only run in the thread
773 SvREFCNT_dec(PL_endav);
776 clone_param.flags = 0;
777 if (SvPOK(init_function)) {
778 thread->init_function = newSV(0);
779 sv_copypv(thread->init_function, init_function);
781 thread->init_function =
782 SvREFCNT_inc(sv_dup(init_function, &clone_param));
785 thread->params = sv_dup(params, &clone_param);
786 SvREFCNT_inc_void(thread->params);
788 /* The code below checks that anything living on the tmps stack and
789 * has been cloned (so it lives in the ptr_table) has a refcount
792 * If the refcount is 0 it means that a something on the stack/context
793 * was holding a reference to it and since we init_stacks() in
794 * perl_clone that won't get cleaned and we will get a leaked scalar.
795 * The reason it was cloned was that it lived on the @_ stack.
797 * Example of this can be found in bugreport 15837 where calls in the
798 * parameter list end up as a temp.
800 * One could argue that this fix should be in perl_clone.
802 while (tmps_ix > 0) {
803 SV* sv = (SV*)ptr_table_fetch(PL_ptr_table, tmps_tmp[tmps_ix]);
805 if (sv && SvREFCNT(sv) == 0) {
806 SvREFCNT_inc_void(sv);
811 SvTEMP_off(thread->init_function);
812 ptr_table_free(PL_ptr_table);
814 PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
816 S_ithread_set(aTHX_ current_thread);
817 PERL_SET_CONTEXT(aTHX);
819 /* Create/start the thread */
821 thread->handle = CreateThread(NULL,
822 (DWORD)thread->stack_size,
825 STACK_SIZE_PARAM_IS_A_RESERVATION,
829 STATIC pthread_attr_t attr;
830 STATIC int attr_inited = 0;
831 STATIC int attr_joinable = PTHREAD_CREATE_JOINABLE;
833 pthread_attr_init(&attr);
837 # ifdef PTHREAD_ATTR_SETDETACHSTATE
838 /* Threads start out joinable */
839 PTHREAD_ATTR_SETDETACHSTATE(&attr, attr_joinable);
842 # ifdef _POSIX_THREAD_ATTR_STACKSIZE
843 /* Set thread's stack size */
844 if (thread->stack_size > 0) {
845 rc_stack_size = pthread_attr_setstacksize(&attr, (size_t)thread->stack_size);
849 /* Create the thread */
850 if (! rc_stack_size) {
851 # ifdef OLD_PTHREADS_API
852 rc_thread_create = pthread_create(&thread->thr,
857 # if defined(HAS_PTHREAD_ATTR_SETSCOPE) && defined(PTHREAD_SCOPE_SYSTEM)
858 pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);
860 rc_thread_create = pthread_create(&thread->thr,
868 /* Now it's safe to accept signals, since we're in our own interpreter's
869 * context and we have created the thread.
871 S_set_sigmask(&thread->initial_sigmask);
874 # ifdef _POSIX_THREAD_ATTR_STACKSIZE
875 /* Try to get thread's actual stack size */
879 stacksize = pthread_attr_getstacksize(attr);
881 if (! pthread_attr_getstacksize(&attr, &stacksize))
884 thread->stack_size = (IV)stacksize;
891 /* Check for errors */
893 if (thread->handle == NULL) {
895 if (rc_stack_size || rc_thread_create) {
897 /* Must unlock mutex for destruct call */
898 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
900 thread->state |= PERL_ITHR_NONVIABLE;
901 S_ithread_free(aTHX_ thread); /* Releases MUTEX */
903 if (ckWARN_d(WARN_THREADS)) {
905 Perl_warn(aTHX_ "Thread creation failed: pthread_attr_setstacksize(%" IVdf ") returned %d", thread->stack_size, rc_stack_size);
907 Perl_warn(aTHX_ "Thread creation failed: pthread_create returned %d", rc_thread_create);
914 MY_POOL.running_threads++;
919 #endif /* USE_ITHREADS */
922 MODULE = threads PACKAGE = threads PREFIX = ithread_
932 SV *function_to_call;
938 SV *thread_exit_only;
944 if ((items >= 2) && SvROK(ST(1)) && SvTYPE(SvRV(ST(1)))==SVt_PVHV) {
946 Perl_croak(aTHX_ "Usage: threads->create(\\%%specs, function, ...)");
948 specs = (HV*)SvRV(ST(1));
952 Perl_croak(aTHX_ "Usage: threads->create(function, ...)");
958 if (sv_isobject(ST(0))) {
960 classname = HvNAME(SvSTASH(SvRV(ST(0))));
961 thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
962 MUTEX_LOCK(&thread->mutex);
963 stack_size = thread->stack_size;
964 exit_opt = thread->state & PERL_ITHR_THREAD_EXIT_ONLY;
965 MUTEX_UNLOCK(&thread->mutex);
967 /* threads->create() */
968 classname = (char *)SvPV_nolen(ST(0));
969 stack_size = MY_POOL.default_stack_size;
970 thread_exit_only = get_sv("threads::thread_exit_only", GV_ADD);
971 exit_opt = (SvTRUE(thread_exit_only))
972 ? PERL_ITHR_THREAD_EXIT_ONLY : 0;
975 function_to_call = ST(idx+1);
980 if (hv_exists(specs, "stack", 5)) {
981 stack_size = SvIV(*hv_fetch(specs, "stack", 5, 0));
982 } else if (hv_exists(specs, "stacksize", 9)) {
983 stack_size = SvIV(*hv_fetch(specs, "stacksize", 9, 0));
984 } else if (hv_exists(specs, "stack_size", 10)) {
985 stack_size = SvIV(*hv_fetch(specs, "stack_size", 10, 0));
989 if (hv_exists(specs, "context", 7)) {
990 str = (char *)SvPV_nolen(*hv_fetch(specs, "context", 7, 0));
1007 Perl_croak(aTHX_ "Invalid context: %s", str);
1009 } else if (hv_exists(specs, "array", 5)) {
1010 if (SvTRUE(*hv_fetch(specs, "array", 5, 0))) {
1013 } else if (hv_exists(specs, "list", 4)) {
1014 if (SvTRUE(*hv_fetch(specs, "list", 4, 0))) {
1017 } else if (hv_exists(specs, "scalar", 6)) {
1018 if (SvTRUE(*hv_fetch(specs, "scalar", 6, 0))) {
1021 } else if (hv_exists(specs, "void", 4)) {
1022 if (SvTRUE(*hv_fetch(specs, "void", 4, 0))) {
1027 /* exit => thread_only */
1028 if (hv_exists(specs, "exit", 4)) {
1029 str = (char *)SvPV_nolen(*hv_fetch(specs, "exit", 4, 0));
1030 exit_opt = (*str == 't' || *str == 'T')
1031 ? PERL_ITHR_THREAD_EXIT_ONLY : 0;
1034 if (context == -1) {
1035 context = GIMME_V; /* Implicit context */
1037 context |= (GIMME_V & (~(G_ARRAY|G_SCALAR|G_VOID)));
1043 for (ii=2; ii < items ; ii++) {
1044 av_push(params, SvREFCNT_inc(ST(idx+ii)));
1049 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
1050 thread = S_ithread_create(aTHX_ function_to_call,
1054 newRV_noinc((SV*)params));
1056 XSRETURN_UNDEF; /* Mutex already unlocked */
1058 ST(0) = sv_2mortal(S_ithread_to_SV(aTHX_ Nullsv, thread, classname, FALSE));
1059 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
1061 /* Let thread run */
1062 MUTEX_UNLOCK(&thread->mutex);
1064 /* XSRETURN(1); - implied */
1074 int want_running = 0;
1078 /* Class method only */
1080 Perl_croak(aTHX_ "Usage: threads->list(...)");
1082 classname = (char *)SvPV_nolen(ST(0));
1084 /* Calling context */
1085 list_context = (GIMME_V == G_ARRAY);
1087 /* Running or joinable parameter */
1089 want_running = SvTRUE(ST(1));
1092 /* Walk through threads list */
1093 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
1094 for (thread = MY_POOL.main_thread.next;
1095 thread != &MY_POOL.main_thread;
1096 thread = thread->next)
1098 MUTEX_LOCK(&thread->mutex);
1099 state = thread->state;
1100 MUTEX_UNLOCK(&thread->mutex);
1102 /* Ignore detached or joined threads */
1103 if (state & PERL_ITHR_UNCALLABLE) {
1107 /* Filter per parameter */
1110 if (state & PERL_ITHR_FINISHED) {
1111 continue; /* Not running */
1114 if (! (state & PERL_ITHR_FINISHED)) {
1115 continue; /* Still running - not joinable yet */
1120 /* Push object on stack if list context */
1122 XPUSHs(sv_2mortal(S_ithread_to_SV(aTHX_ Nullsv, thread, classname, TRUE)));
1126 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
1127 /* If scalar context, send back count */
1128 if (! list_context) {
1139 /* Class method only */
1140 if ((items != 1) || SvROK(ST(0))) {
1141 Perl_croak(aTHX_ "Usage: threads->self()");
1143 classname = (char *)SvPV_nolen(ST(0));
1145 thread = S_ithread_get(aTHX);
1147 ST(0) = sv_2mortal(S_ithread_to_SV(aTHX_ Nullsv, thread, classname, TRUE));
1148 /* XSRETURN(1); - implied */
1156 PERL_UNUSED_VAR(items);
1157 thread = S_SV_to_ithread(aTHX_ ST(0));
1158 XST_mUV(0, thread->tid);
1159 /* XSRETURN(1); - implied */
1166 ithread *current_thread;
1177 /* Object method only */
1178 if ((items != 1) || ! sv_isobject(ST(0))) {
1179 Perl_croak(aTHX_ "Usage: $thr->join()");
1182 /* Check if the thread is joinable and not ourselves */
1183 thread = S_SV_to_ithread(aTHX_ ST(0));
1184 current_thread = S_ithread_get(aTHX);
1186 MUTEX_LOCK(&thread->mutex);
1187 if ((join_err = (thread->state & PERL_ITHR_UNCALLABLE))) {
1188 MUTEX_UNLOCK(&thread->mutex);
1189 Perl_croak(aTHX_ (join_err & PERL_ITHR_DETACHED)
1190 ? "Cannot join a detached thread"
1191 : "Thread already joined");
1192 } else if (thread->tid == current_thread->tid) {
1193 MUTEX_UNLOCK(&thread->mutex);
1194 Perl_croak(aTHX_ "Cannot join self");
1197 /* Mark as joined */
1198 thread->state |= PERL_ITHR_JOINED;
1199 MUTEX_UNLOCK(&thread->mutex);
1201 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
1202 MY_POOL.joinable_threads--;
1203 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
1205 /* Join the thread */
1207 if (WaitForSingleObject(thread->handle, INFINITE) != WAIT_OBJECT_0) {
1208 /* Timeout/abandonment unexpected here; check $^E */
1209 Perl_croak(aTHX_ "PANIC: underlying join failed");
1212 if ((rc_join = pthread_join(thread->thr, &retval)) != 0) {
1213 /* In progress/deadlock/unknown unexpected here; check $! */
1215 Perl_croak(aTHX_ "PANIC: underlying join failed");
1219 MUTEX_LOCK(&thread->mutex);
1220 /* Get the return value from the call_sv */
1221 /* Objects do not survive this process - FIXME */
1222 if ((thread->gimme & G_WANT) != G_VOID) {
1224 PerlInterpreter *other_perl;
1225 CLONE_PARAMS clone_params;
1227 params_copy = (AV *)SvRV(thread->params);
1228 other_perl = thread->interp;
1229 clone_params.stashes = newAV();
1230 clone_params.flags = CLONEf_JOIN_IN;
1231 PL_ptr_table = ptr_table_new();
1232 S_ithread_set(aTHX_ thread);
1233 /* Ensure 'meaningful' addresses retain their meaning */
1234 ptr_table_store(PL_ptr_table, &other_perl->Isv_undef, &PL_sv_undef);
1235 ptr_table_store(PL_ptr_table, &other_perl->Isv_no, &PL_sv_no);
1236 ptr_table_store(PL_ptr_table, &other_perl->Isv_yes, &PL_sv_yes);
1237 params = (AV *)sv_dup((SV*)params_copy, &clone_params);
1238 S_ithread_set(aTHX_ current_thread);
1239 SvREFCNT_dec(clone_params.stashes);
1240 SvREFCNT_inc_void(params);
1241 ptr_table_free(PL_ptr_table);
1242 PL_ptr_table = NULL;
1245 /* If thread didn't die, then we can free its interpreter */
1246 if (! (thread->state & PERL_ITHR_DIED)) {
1247 S_ithread_clear(aTHX_ thread);
1249 S_ithread_free(aTHX_ thread); /* Releases MUTEX */
1251 /* If no return values, then just return */
1256 /* Put return values on stack */
1257 len = (int)AvFILL(params);
1258 for (ii=0; ii <= len; ii++) {
1259 SV* param = av_shift(params);
1260 XPUSHs(sv_2mortal(param));
1263 /* Free return value array */
1264 SvREFCNT_dec(params);
1270 PERL_UNUSED_VAR(items);
1281 PERL_UNUSED_VAR(items);
1283 /* Detach the thread */
1284 thread = S_SV_to_ithread(aTHX_ ST(0));
1285 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
1286 MUTEX_LOCK(&thread->mutex);
1287 if (! (detach_err = (thread->state & PERL_ITHR_UNCALLABLE))) {
1288 /* Thread is detachable */
1289 thread->state |= PERL_ITHR_DETACHED;
1291 /* Windows has no 'detach thread' function */
1293 PERL_THREAD_DETACH(thread->thr);
1295 if (thread->state & PERL_ITHR_FINISHED) {
1296 MY_POOL.joinable_threads--;
1298 MY_POOL.running_threads--;
1299 MY_POOL.detached_threads++;
1302 MUTEX_UNLOCK(&thread->mutex);
1303 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
1306 Perl_croak(aTHX_ (detach_err & PERL_ITHR_DETACHED)
1307 ? "Thread already detached"
1308 : "Cannot detach a joined thread");
1311 /* If thread is finished and didn't die,
1312 * then we can free its interpreter */
1313 MUTEX_LOCK(&thread->mutex);
1314 if ((thread->state & PERL_ITHR_FINISHED) &&
1315 ! (thread->state & PERL_ITHR_DIED))
1317 S_ithread_clear(aTHX_ thread);
1319 S_ithread_free(aTHX_ thread); /* Releases MUTEX */
1329 /* Must have safe signals */
1330 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG) {
1331 Perl_croak(aTHX_ "Cannot signal threads without safe signals");
1334 /* Object method only */
1335 if ((items != 2) || ! sv_isobject(ST(0))) {
1336 Perl_croak(aTHX_ "Usage: $thr->kill('SIG...')");
1340 sig_name = SvPV_nolen(ST(1));
1341 if (isALPHA(*sig_name)) {
1342 if (*sig_name == 'S' && sig_name[1] == 'I' && sig_name[2] == 'G') {
1345 if ((signal = whichsig(sig_name)) < 0) {
1346 Perl_croak(aTHX_ "Unrecognized signal name: %s", sig_name);
1349 signal = SvIV(ST(1));
1352 /* Set the signal for the thread */
1353 thread = S_SV_to_ithread(aTHX_ ST(0));
1354 MUTEX_LOCK(&thread->mutex);
1355 if (thread->interp) {
1356 dTHXa(thread->interp);
1357 PL_psig_pend[signal]++;
1360 MUTEX_UNLOCK(&thread->mutex);
1362 /* Return the thread to allow for method chaining */
1364 /* XSRETURN(1); - implied */
1368 ithread_DESTROY(...)
1370 PERL_UNUSED_VAR(items);
1371 sv_unmagic(SvRV(ST(0)), PERL_MAGIC_shared_scalar);
1379 PERL_UNUSED_VAR(items);
1381 /* Compares TIDs to determine thread equality */
1382 if (sv_isobject(ST(0)) && sv_isobject(ST(1))) {
1383 ithread *thr1 = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1384 ithread *thr2 = INT2PTR(ithread *, SvIV(SvRV(ST(1))));
1385 are_equal = (thr1->tid == thr2->tid);
1390 /* Return 0 on false for backward compatibility */
1393 /* XSRETURN(1); - implied */
1406 /* Class method only */
1408 Perl_croak(aTHX_ "Usage: threads->object($tid)");
1410 classname = (char *)SvPV_nolen(ST(0));
1412 if ((items < 2) || ! SvOK(ST(1))) {
1416 /* threads->object($tid) */
1419 /* Walk through threads list */
1420 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
1421 for (thread = MY_POOL.main_thread.next;
1422 thread != &MY_POOL.main_thread;
1423 thread = thread->next)
1426 if (thread->tid == tid) {
1427 /* Ignore if detached or joined */
1428 MUTEX_LOCK(&thread->mutex);
1429 state = thread->state;
1430 MUTEX_UNLOCK(&thread->mutex);
1431 if (! (state & PERL_ITHR_UNCALLABLE)) {
1432 /* Put object on stack */
1433 ST(0) = sv_2mortal(S_ithread_to_SV(aTHX_ Nullsv, thread, classname, TRUE));
1439 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
1444 /* XSRETURN(1); - implied */
1448 ithread__handle(...);
1452 PERL_UNUSED_VAR(items);
1453 thread = S_SV_to_ithread(aTHX_ ST(0));
1455 XST_mUV(0, PTR2UV(&thread->handle));
1457 XST_mUV(0, PTR2UV(&thread->thr));
1459 /* XSRETURN(1); - implied */
1463 ithread_get_stack_size(...)
1468 PERL_UNUSED_VAR(items);
1469 if (sv_isobject(ST(0))) {
1470 /* $thr->get_stack_size() */
1471 ithread *thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1472 stack_size = thread->stack_size;
1474 /* threads->get_stack_size() */
1475 stack_size = MY_POOL.default_stack_size;
1477 XST_mIV(0, stack_size);
1478 /* XSRETURN(1); - implied */
1482 ithread_set_stack_size(...)
1488 Perl_croak(aTHX_ "Usage: threads->set_stack_size($size)");
1490 if (sv_isobject(ST(0))) {
1491 Perl_croak(aTHX_ "Cannot change stack size of an existing thread");
1493 if (! looks_like_number(ST(1))) {
1494 Perl_croak(aTHX_ "Stack size must be numeric");
1497 old_size = MY_POOL.default_stack_size;
1498 MY_POOL.default_stack_size = S_good_stack_size(aTHX_ SvIV(ST(1)));
1499 XST_mIV(0, old_size);
1500 /* XSRETURN(1); - implied */
1504 ithread_is_running(...)
1508 /* Object method only */
1509 if ((items != 1) || ! sv_isobject(ST(0))) {
1510 Perl_croak(aTHX_ "Usage: $thr->is_running()");
1513 thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1514 MUTEX_LOCK(&thread->mutex);
1515 ST(0) = (thread->state & PERL_ITHR_FINISHED) ? &PL_sv_no : &PL_sv_yes;
1516 MUTEX_UNLOCK(&thread->mutex);
1517 /* XSRETURN(1); - implied */
1521 ithread_is_detached(...)
1525 PERL_UNUSED_VAR(items);
1526 thread = S_SV_to_ithread(aTHX_ ST(0));
1527 MUTEX_LOCK(&thread->mutex);
1528 ST(0) = (thread->state & PERL_ITHR_DETACHED) ? &PL_sv_yes : &PL_sv_no;
1529 MUTEX_UNLOCK(&thread->mutex);
1530 /* XSRETURN(1); - implied */
1534 ithread_is_joinable(...)
1538 /* Object method only */
1539 if ((items != 1) || ! sv_isobject(ST(0))) {
1540 Perl_croak(aTHX_ "Usage: $thr->is_joinable()");
1543 thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1544 MUTEX_LOCK(&thread->mutex);
1545 ST(0) = ((thread->state & PERL_ITHR_FINISHED) &&
1546 ! (thread->state & PERL_ITHR_UNCALLABLE))
1547 ? &PL_sv_yes : &PL_sv_no;
1548 MUTEX_UNLOCK(&thread->mutex);
1549 /* XSRETURN(1); - implied */
1553 ithread_wantarray(...)
1557 PERL_UNUSED_VAR(items);
1558 thread = S_SV_to_ithread(aTHX_ ST(0));
1559 ST(0) = ((thread->gimme & G_WANT) == G_ARRAY) ? &PL_sv_yes :
1560 ((thread->gimme & G_WANT) == G_VOID) ? &PL_sv_undef
1561 /* G_SCALAR */ : &PL_sv_no;
1562 /* XSRETURN(1); - implied */
1566 ithread_set_thread_exit_only(...)
1571 Perl_croak(aTHX_ "Usage: ->set_thread_exit_only(boolean)");
1573 thread = S_SV_to_ithread(aTHX_ ST(0));
1574 MUTEX_LOCK(&thread->mutex);
1575 if (SvTRUE(ST(1))) {
1576 thread->state |= PERL_ITHR_THREAD_EXIT_ONLY;
1578 thread->state &= ~PERL_ITHR_THREAD_EXIT_ONLY;
1580 MUTEX_UNLOCK(&thread->mutex);
1589 /* Object method only */
1590 if ((items != 1) || ! sv_isobject(ST(0))) {
1591 Perl_croak(aTHX_ "Usage: $thr->err()");
1594 thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1595 MUTEX_LOCK(&thread->mutex);
1597 /* If thread died, then clone the error into the calling thread */
1598 if (thread->state & PERL_ITHR_DIED) {
1599 PerlInterpreter *other_perl;
1600 CLONE_PARAMS clone_params;
1601 ithread *current_thread;
1603 other_perl = thread->interp;
1604 clone_params.stashes = newAV();
1605 clone_params.flags = CLONEf_JOIN_IN;
1606 PL_ptr_table = ptr_table_new();
1607 current_thread = S_ithread_get(aTHX);
1608 S_ithread_set(aTHX_ thread);
1609 /* Ensure 'meaningful' addresses retain their meaning */
1610 ptr_table_store(PL_ptr_table, &other_perl->Isv_undef, &PL_sv_undef);
1611 ptr_table_store(PL_ptr_table, &other_perl->Isv_no, &PL_sv_no);
1612 ptr_table_store(PL_ptr_table, &other_perl->Isv_yes, &PL_sv_yes);
1613 err = sv_dup(thread->err, &clone_params);
1614 S_ithread_set(aTHX_ current_thread);
1615 SvREFCNT_dec(clone_params.stashes);
1616 SvREFCNT_inc_void(err);
1617 /* If error was an object, bless it into the correct class */
1618 if (thread->err_class) {
1619 sv_bless(err, gv_stashpv(thread->err_class, 1));
1621 ptr_table_free(PL_ptr_table);
1622 PL_ptr_table = NULL;
1625 MUTEX_UNLOCK(&thread->mutex);
1631 ST(0) = sv_2mortal(err);
1632 /* XSRETURN(1); - implied */
1635 #endif /* USE_ITHREADS */
1641 SV *my_pool_sv = *hv_fetch(PL_modglobal, MY_POOL_KEY,
1642 sizeof(MY_POOL_KEY)-1, TRUE);
1643 my_pool_t *my_poolp = (my_pool_t*)SvPVX(newSV(sizeof(my_pool_t)-1));
1647 Zero(my_poolp, 1, my_pool_t);
1648 sv_setuv(my_pool_sv, PTR2UV(my_poolp));
1650 PL_perl_destruct_level = 2;
1651 MUTEX_INIT(&MY_POOL.create_destruct_mutex);
1652 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
1654 PL_threadhook = &Perl_ithread_hook;
1656 MY_POOL.tid_counter = 1;
1657 # ifdef THREAD_CREATE_NEEDS_STACK
1658 MY_POOL.default_stack_size = THREAD_CREATE_NEEDS_STACK;
1661 /* The 'main' thread is thread 0.
1662 * It is detached (unjoinable) and immortal.
1665 MUTEX_INIT(&MY_POOL.main_thread.mutex);
1667 /* Head of the threads list */
1668 MY_POOL.main_thread.next = &MY_POOL.main_thread;
1669 MY_POOL.main_thread.prev = &MY_POOL.main_thread;
1671 MY_POOL.main_thread.count = 1; /* Immortal */
1673 MY_POOL.main_thread.interp = aTHX;
1674 MY_POOL.main_thread.state = PERL_ITHR_DETACHED; /* Detached */
1675 MY_POOL.main_thread.stack_size = MY_POOL.default_stack_size;
1677 MY_POOL.main_thread.thr = GetCurrentThreadId();
1679 MY_POOL.main_thread.thr = pthread_self();
1682 S_ithread_set(aTHX_ &MY_POOL.main_thread);
1683 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
1684 #endif /* USE_ITHREADS */