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 return pthread_sigmask(SIG_BLOCK, &newmask, oldmask);
145 /* Set the signal mask for this thread to newmask */
147 S_set_sigmask(sigset_t *newmask)
150 /* XXX: How to do this on win32? */
153 return pthread_sigmask(SIG_SETMASK, newmask, NULL);
157 /* Used by Perl interpreter for thread context switching */
159 S_ithread_set(pTHX_ ithread *thread)
162 MY_CXT.context = thread;
169 return (MY_CXT.context);
173 /* Free any data (such as the Perl interpreter) attached to an ithread
174 * structure. This is a bit like undef on SVs, where the SV isn't freed,
175 * but the PVX is. Must be called with thread->mutex already locked. Also,
176 * must be called with MY_POOL.create_destruct_mutex unlocked as destruction
177 * of the interpreter can lead to recursive destruction calls that could
178 * lead to a deadlock on that mutex.
181 S_ithread_clear(pTHX_ ithread *thread)
183 PerlInterpreter *interp;
186 assert(((thread->state & PERL_ITHR_FINISHED) &&
187 (thread->state & PERL_ITHR_UNCALLABLE))
189 (thread->state & PERL_ITHR_NONVIABLE));
191 /* We temporarily set the interpreter context to the interpreter being
192 * destroyed. It's in no condition to handle signals while it's being
195 S_block_most_signals(&origmask);
197 interp = thread->interp;
201 PERL_SET_CONTEXT(interp);
202 S_ithread_set(aTHX_ thread);
204 SvREFCNT_dec(thread->params);
205 thread->params = Nullsv;
208 SvREFCNT_dec(thread->err);
209 thread->err = Nullsv;
212 perl_destruct(interp);
214 thread->interp = NULL;
217 PERL_SET_CONTEXT(aTHX);
218 S_set_sigmask(&origmask);
222 /* Decrement the refcount of an ithread, and if it reaches zero, free it.
223 * Must be called with the mutex held.
224 * On return, mutex is released (or destroyed).
227 S_ithread_free(pTHX_ ithread *thread)
234 if (! (thread->state & PERL_ITHR_NONVIABLE)) {
235 assert(thread->count > 0);
236 if (--thread->count > 0) {
237 MUTEX_UNLOCK(&thread->mutex);
240 assert((thread->state & PERL_ITHR_FINISHED) &&
241 (thread->state & PERL_ITHR_UNCALLABLE));
243 MUTEX_UNLOCK(&thread->mutex);
245 /* Main thread (0) is immortal and should never get here */
246 assert(thread->tid != 0);
248 /* Remove from circular list of threads */
249 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
250 assert(thread->prev && thread->next);
251 thread->next->prev = thread->prev;
252 thread->prev->next = thread->next;
255 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
257 /* Thread is now disowned */
258 MUTEX_LOCK(&thread->mutex);
259 S_ithread_clear(aTHX_ thread);
262 handle = thread->handle;
263 thread->handle = NULL;
265 MUTEX_UNLOCK(&thread->mutex);
266 MUTEX_DESTROY(&thread->mutex);
274 PerlMemShared_free(thread);
276 /* total_threads >= 1 is used to veto cleanup by the main thread,
277 * should it happen to exit while other threads still exist.
278 * Decrement this as the very last thing in the thread's existence.
279 * Otherwise, MY_POOL and global state such as PL_op_mutex may get
280 * freed while we're still using it.
282 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
283 MY_POOL.total_threads--;
284 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
289 S_ithread_count_inc(pTHX_ ithread *thread)
291 MUTEX_LOCK(&thread->mutex);
293 MUTEX_UNLOCK(&thread->mutex);
297 /* Warn if exiting with any unjoined threads */
301 int veto_cleanup, warn;
304 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
305 veto_cleanup = (MY_POOL.total_threads > 0);
306 warn = (MY_POOL.running_threads || MY_POOL.joinable_threads);
307 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
310 if (ckWARN_d(WARN_THREADS)) {
311 Perl_warn(aTHX_ "Perl exited with active threads:\n\t%"
312 IVdf " running and unjoined\n\t%"
313 IVdf " finished and unjoined\n\t%"
314 IVdf " running and detached\n",
315 MY_POOL.running_threads,
316 MY_POOL.joinable_threads,
317 MY_POOL.detached_threads);
321 return (veto_cleanup);
325 /* Called from perl_destruct() in each thread. If it's the main thread,
326 * stop it from freeing everything if there are other threads still running.
329 Perl_ithread_hook(pTHX)
332 return ((aTHX == MY_POOL.main_thread.interp) ? S_exit_warning(aTHX) : 0);
336 /* MAGIC (in mg.h sense) hooks */
339 ithread_mg_get(pTHX_ SV *sv, MAGIC *mg)
341 ithread *thread = (ithread *)mg->mg_ptr;
342 SvIV_set(sv, PTR2IV(thread));
348 ithread_mg_free(pTHX_ SV *sv, MAGIC *mg)
350 ithread *thread = (ithread *)mg->mg_ptr;
351 MUTEX_LOCK(&thread->mutex);
352 S_ithread_free(aTHX_ thread); /* Releases MUTEX */
357 ithread_mg_dup(pTHX_ MAGIC *mg, CLONE_PARAMS *param)
359 S_ithread_count_inc(aTHX_ (ithread *)mg->mg_ptr);
363 MGVTBL ithread_vtbl = {
364 ithread_mg_get, /* get */
368 ithread_mg_free, /* free */
370 ithread_mg_dup /* dup */
374 /* Provided default, minimum and rational stack sizes */
376 S_good_stack_size(pTHX_ IV stack_size)
380 /* Use default stack size if no stack size specified */
382 return (MY_POOL.default_stack_size);
385 #ifdef PTHREAD_STACK_MIN
386 /* Can't use less than minimum */
387 if (stack_size < PTHREAD_STACK_MIN) {
388 if (ckWARN(WARN_THREADS)) {
389 Perl_warn(aTHX_ "Using minimum thread stack size of %" IVdf, (IV)PTHREAD_STACK_MIN);
391 return (PTHREAD_STACK_MIN);
395 /* Round up to page size boundary */
396 if (MY_POOL.page_size <= 0) {
397 #if defined(HAS_SYSCONF) && (defined(_SC_PAGESIZE) || defined(_SC_MMAP_PAGE_SIZE))
398 SETERRNO(0, SS_NORMAL);
400 MY_POOL.page_size = sysconf(_SC_PAGESIZE);
402 MY_POOL.page_size = sysconf(_SC_MMAP_PAGE_SIZE);
404 if ((long)MY_POOL.page_size < 0) {
406 SV * const error = get_sv("@", 0);
407 (void)SvUPGRADE(error, SVt_PV);
408 Perl_croak(aTHX_ "PANIC: sysconf: %s", SvPV_nolen(error));
410 Perl_croak(aTHX_ "PANIC: sysconf: pagesize unknown");
414 # ifdef HAS_GETPAGESIZE
415 MY_POOL.page_size = getpagesize();
417 # if defined(I_SYS_PARAM) && defined(PAGESIZE)
418 MY_POOL.page_size = PAGESIZE;
420 MY_POOL.page_size = 8192; /* A conservative default */
423 if (MY_POOL.page_size <= 0) {
424 Perl_croak(aTHX_ "PANIC: bad pagesize %" IVdf, (IV)MY_POOL.page_size);
428 stack_size = ((stack_size + (MY_POOL.page_size - 1)) / MY_POOL.page_size) * MY_POOL.page_size;
434 /* Starts executing the thread.
435 * Passed as the C level function to run in the new thread.
438 STATIC THREAD_RET_TYPE
439 S_ithread_run(LPVOID arg)
442 S_ithread_run(void * arg)
445 ithread *thread = (ithread *)arg;
448 int exit_app = 0; /* Thread terminated using 'exit' */
450 int died = 0; /* Thread terminated abnormally */
454 dTHXa(thread->interp);
458 /* Blocked until ->create() call finishes */
459 MUTEX_LOCK(&thread->mutex);
460 MUTEX_UNLOCK(&thread->mutex);
462 PERL_SET_CONTEXT(thread->interp);
463 S_ithread_set(aTHX_ thread);
465 /* Thread starts with most signals blocked - restore the signal mask from
466 * the ithread struct.
468 S_set_sigmask(&thread->initial_sigmask);
470 PL_perl_destruct_level = 2;
473 AV *params = (AV *)SvRV(thread->params);
474 int len = (int)av_len(params)+1;
481 /* Put args on the stack */
483 for (ii=0; ii < len; ii++) {
484 XPUSHs(av_shift(params));
488 oldscope = PL_scopestack_ix;
491 /* Run the specified function */
492 len = (int)call_sv(thread->init_function, thread->gimme|G_EVAL);
493 } else if (jmp_rc == 2) {
496 exit_code = STATUS_CURRENT;
497 while (PL_scopestack_ix > oldscope) {
503 /* The interpreter is finished, so this thread can stop receiving
504 * signals. This way, our signal handler doesn't get called in the
505 * middle of our parent thread calling perl_destruct()...
507 S_block_most_signals(NULL);
509 /* Remove args from stack and put back in params array */
511 for (ii=len-1; ii >= 0; ii--) {
513 if (jmp_rc == 0 && (thread->gimme & G_WANT) != G_VOID) {
514 av_store(params, ii, SvREFCNT_inc(sv));
521 /* Check for abnormal termination */
523 died = PERL_ITHR_DIED;
524 thread->err = newSVsv(ERRSV);
525 /* If ERRSV is an object, remember the classname and then
526 * rebless into 'main' so it will survive 'cloning'
528 if (sv_isobject(thread->err)) {
529 thread->err_class = HvNAME(SvSTASH(SvRV(thread->err)));
530 sv_bless(thread->err, gv_stashpv("main", 0));
533 if (ckWARN_d(WARN_THREADS)) {
534 oldscope = PL_scopestack_ix;
537 /* Warn that thread died */
538 Perl_warn(aTHX_ "Thread %" UVuf " terminated abnormally: %" SVf, thread->tid, ERRSV);
539 } else if (jmp_rc == 2) {
540 /* Warn handler exited */
542 exit_code = STATUS_CURRENT;
543 while (PL_scopestack_ix > oldscope) {
551 /* Release function ref */
552 SvREFCNT_dec(thread->init_function);
553 thread->init_function = Nullsv;
556 PerlIO_flush((PerlIO *)NULL);
558 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
559 MUTEX_LOCK(&thread->mutex);
560 /* Mark as finished */
561 thread->state |= (PERL_ITHR_FINISHED | died);
562 /* Clear exit flag if required */
563 if (thread->state & PERL_ITHR_THREAD_EXIT_ONLY) {
567 /* Adjust thread status counts */
568 if (thread->state & PERL_ITHR_DETACHED) {
569 MY_POOL.detached_threads--;
571 MY_POOL.running_threads--;
572 MY_POOL.joinable_threads++;
574 MUTEX_UNLOCK(&thread->mutex);
575 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
577 /* Exit application if required */
579 oldscope = PL_scopestack_ix;
582 /* Warn if there are unjoined threads */
583 S_exit_warning(aTHX);
584 } else if (jmp_rc == 2) {
585 /* Warn handler exited */
586 exit_code = STATUS_CURRENT;
587 while (PL_scopestack_ix > oldscope) {
596 /* At this point, the interpreter may have been freed, so call
597 * free in the the context of of the 'main' interpreter which
598 * can't have been freed due to the veto_cleanup mechanism.
600 aTHX = MY_POOL.main_thread.interp;
602 MUTEX_LOCK(&thread->mutex);
603 S_ithread_free(aTHX_ thread); /* Releases MUTEX */
613 /* Type conversion helper functions */
616 S_ithread_to_SV(pTHX_ SV *obj, ithread *thread, char *classname, bool inc)
622 S_ithread_count_inc(aTHX_ thread);
628 sv = newSVrv(obj, classname);
629 sv_setiv(sv, PTR2IV(thread));
630 mg = sv_magicext(sv, Nullsv, PERL_MAGIC_shared_scalar, &ithread_vtbl, (char *)thread, 0);
631 mg->mg_flags |= MGf_DUP;
638 S_SV_to_ithread(pTHX_ SV *sv)
640 /* Argument is a thread */
642 return (INT2PTR(ithread *, SvIV(SvRV(sv))));
644 /* Argument is classname, therefore return current thread */
645 return (S_ithread_get(aTHX));
650 * Called in context of parent thread.
651 * Called with MY_POOL.create_destruct_mutex locked. (Unlocked on error.)
655 pTHX_ SV *init_function,
662 ithread *current_thread = S_ithread_get(aTHX);
664 SV **tmps_tmp = PL_tmps_stack;
665 IV tmps_ix = PL_tmps_ix;
667 int rc_stack_size = 0;
668 int rc_thread_create = 0;
672 /* Allocate thread structure in context of the main thread's interpreter */
674 PERL_SET_CONTEXT(MY_POOL.main_thread.interp);
675 thread = (ithread *)PerlMemShared_malloc(sizeof(ithread));
677 PERL_SET_CONTEXT(aTHX);
679 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
680 PerlLIO_write(PerlIO_fileno(Perl_error_log), PL_no_mem, strlen(PL_no_mem));
683 Zero(thread, 1, ithread);
685 /* Add to threads list */
686 thread->next = &MY_POOL.main_thread;
687 thread->prev = MY_POOL.main_thread.prev;
688 MY_POOL.main_thread.prev = thread;
689 thread->prev->next = thread;
690 MY_POOL.total_threads++;
692 /* 1 ref to be held by the local var 'thread' in S_ithread_run().
693 * 1 ref to be held by the threads object that we assume we will
694 * be embedded in upon our return.
695 * 1 ref to be the responsibility of join/detach, so we don't get
696 * freed until join/detach, even if no thread objects remain.
697 * This allows the following to work:
698 * { threads->create(sub{...}); } threads->object(1)->join;
702 /* Block new thread until ->create() call finishes */
703 MUTEX_INIT(&thread->mutex);
704 MUTEX_LOCK(&thread->mutex);
706 thread->tid = MY_POOL.tid_counter++;
707 thread->stack_size = S_good_stack_size(aTHX_ stack_size);
708 thread->gimme = gimme;
709 thread->state = exit_opt;
711 /* "Clone" our interpreter into the thread's interpreter.
712 * This gives thread access to "static data" and code.
714 PerlIO_flush((PerlIO *)NULL);
715 S_ithread_set(aTHX_ thread);
717 SAVEBOOL(PL_srand_called); /* Save this so it becomes the correct value */
718 PL_srand_called = FALSE; /* Set it to false so we can detect if it gets
719 set during the clone */
721 /* perl_clone() will leave us the new interpreter's context. This poses
722 * two problems for our signal handler. First, it sets the new context
723 * before the new interpreter struct is fully initialized, so our signal
724 * handler might find bogus data in the interpreter struct it gets.
725 * Second, even if the interpreter is initialized before a signal comes in,
726 * we would like to avoid that interpreter receiving notifications for
727 * signals (especially when they ought to be for the one running in this
728 * thread), until it is running in its own thread. Another problem is that
729 * the new thread will not have set the context until some time after it
730 * has started, so it won't be safe for our signal handler to run until
733 * So we block most signals here, so the new thread will inherit the signal
734 * mask, and unblock them right after the thread creation. The original
735 * mask is saved in the thread struct so that the new thread can restore
738 S_block_most_signals(&thread->initial_sigmask);
741 thread->interp = perl_clone(aTHX, CLONEf_KEEP_PTR_TABLE | CLONEf_CLONE_HOST);
743 thread->interp = perl_clone(aTHX, CLONEf_KEEP_PTR_TABLE);
746 /* perl_clone() leaves us in new interpreter's context. As it is tricky
747 * to spot an implicit aTHX, create a new scope with aTHX matching the
748 * context for the duration of our work for new interpreter.
751 CLONE_PARAMS clone_param;
753 dTHXa(thread->interp);
757 /* Here we remove END blocks since they should only run in the thread
760 SvREFCNT_dec(PL_endav);
763 clone_param.flags = 0;
764 if (SvPOK(init_function)) {
765 thread->init_function = newSV(0);
766 sv_copypv(thread->init_function, init_function);
768 thread->init_function =
769 SvREFCNT_inc(sv_dup(init_function, &clone_param));
772 thread->params = sv_dup(params, &clone_param);
773 SvREFCNT_inc_void(thread->params);
775 /* The code below checks that anything living on the tmps stack and
776 * has been cloned (so it lives in the ptr_table) has a refcount
779 * If the refcount is 0 it means that a something on the stack/context
780 * was holding a reference to it and since we init_stacks() in
781 * perl_clone that won't get cleaned and we will get a leaked scalar.
782 * The reason it was cloned was that it lived on the @_ stack.
784 * Example of this can be found in bugreport 15837 where calls in the
785 * parameter list end up as a temp.
787 * One could argue that this fix should be in perl_clone.
789 while (tmps_ix > 0) {
790 SV* sv = (SV*)ptr_table_fetch(PL_ptr_table, tmps_tmp[tmps_ix]);
792 if (sv && SvREFCNT(sv) == 0) {
793 SvREFCNT_inc_void(sv);
798 SvTEMP_off(thread->init_function);
799 ptr_table_free(PL_ptr_table);
801 PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
803 S_ithread_set(aTHX_ current_thread);
804 PERL_SET_CONTEXT(aTHX);
806 /* Create/start the thread */
808 thread->handle = CreateThread(NULL,
809 (DWORD)thread->stack_size,
812 STACK_SIZE_PARAM_IS_A_RESERVATION,
816 STATIC pthread_attr_t attr;
817 STATIC int attr_inited = 0;
818 STATIC int attr_joinable = PTHREAD_CREATE_JOINABLE;
820 pthread_attr_init(&attr);
824 # ifdef PTHREAD_ATTR_SETDETACHSTATE
825 /* Threads start out joinable */
826 PTHREAD_ATTR_SETDETACHSTATE(&attr, attr_joinable);
829 # ifdef _POSIX_THREAD_ATTR_STACKSIZE
830 /* Set thread's stack size */
831 if (thread->stack_size > 0) {
832 rc_stack_size = pthread_attr_setstacksize(&attr, (size_t)thread->stack_size);
836 /* Create the thread */
837 if (! rc_stack_size) {
838 # ifdef OLD_PTHREADS_API
839 rc_thread_create = pthread_create(&thread->thr,
844 # if defined(HAS_PTHREAD_ATTR_SETSCOPE) && defined(PTHREAD_SCOPE_SYSTEM)
845 pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);
847 rc_thread_create = pthread_create(&thread->thr,
854 /* Now it's safe to accept signals, since we're in our own interpreter's
855 * context and we have created the thread.
857 S_set_sigmask(&thread->initial_sigmask);
859 # ifdef _POSIX_THREAD_ATTR_STACKSIZE
860 /* Try to get thread's actual stack size */
864 stacksize = pthread_attr_getstacksize(attr);
866 if (! pthread_attr_getstacksize(&attr, &stacksize))
869 thread->stack_size = (IV)stacksize;
876 /* Check for errors */
878 if (thread->handle == NULL) {
880 if (rc_stack_size || rc_thread_create) {
882 /* Must unlock mutex for destruct call */
883 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
885 thread->state |= PERL_ITHR_NONVIABLE;
886 S_ithread_free(aTHX_ thread); /* Releases MUTEX */
888 if (ckWARN_d(WARN_THREADS)) {
890 Perl_warn(aTHX_ "Thread creation failed: pthread_attr_setstacksize(%" IVdf ") returned %d", thread->stack_size, rc_stack_size);
892 Perl_warn(aTHX_ "Thread creation failed: pthread_create returned %d", rc_thread_create);
899 MY_POOL.running_threads++;
904 #endif /* USE_ITHREADS */
907 MODULE = threads PACKAGE = threads PREFIX = ithread_
917 SV *function_to_call;
923 SV *thread_exit_only;
929 if ((items >= 2) && SvROK(ST(1)) && SvTYPE(SvRV(ST(1)))==SVt_PVHV) {
931 Perl_croak(aTHX_ "Usage: threads->create(\\%%specs, function, ...)");
933 specs = (HV*)SvRV(ST(1));
937 Perl_croak(aTHX_ "Usage: threads->create(function, ...)");
943 if (sv_isobject(ST(0))) {
945 classname = HvNAME(SvSTASH(SvRV(ST(0))));
946 thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
947 MUTEX_LOCK(&thread->mutex);
948 stack_size = thread->stack_size;
949 exit_opt = thread->state & PERL_ITHR_THREAD_EXIT_ONLY;
950 MUTEX_UNLOCK(&thread->mutex);
952 /* threads->create() */
953 classname = (char *)SvPV_nolen(ST(0));
954 stack_size = MY_POOL.default_stack_size;
955 thread_exit_only = get_sv("threads::thread_exit_only", GV_ADD);
956 exit_opt = (SvTRUE(thread_exit_only))
957 ? PERL_ITHR_THREAD_EXIT_ONLY : 0;
960 function_to_call = ST(idx+1);
965 if (hv_exists(specs, "stack", 5)) {
966 stack_size = SvIV(*hv_fetch(specs, "stack", 5, 0));
967 } else if (hv_exists(specs, "stacksize", 9)) {
968 stack_size = SvIV(*hv_fetch(specs, "stacksize", 9, 0));
969 } else if (hv_exists(specs, "stack_size", 10)) {
970 stack_size = SvIV(*hv_fetch(specs, "stack_size", 10, 0));
974 if (hv_exists(specs, "context", 7)) {
975 str = (char *)SvPV_nolen(*hv_fetch(specs, "context", 7, 0));
992 Perl_croak(aTHX_ "Invalid context: %s", str);
994 } else if (hv_exists(specs, "array", 5)) {
995 if (SvTRUE(*hv_fetch(specs, "array", 5, 0))) {
998 } else if (hv_exists(specs, "list", 4)) {
999 if (SvTRUE(*hv_fetch(specs, "list", 4, 0))) {
1002 } else if (hv_exists(specs, "scalar", 6)) {
1003 if (SvTRUE(*hv_fetch(specs, "scalar", 6, 0))) {
1006 } else if (hv_exists(specs, "void", 4)) {
1007 if (SvTRUE(*hv_fetch(specs, "void", 4, 0))) {
1012 /* exit => thread_only */
1013 if (hv_exists(specs, "exit", 4)) {
1014 str = (char *)SvPV_nolen(*hv_fetch(specs, "exit", 4, 0));
1015 exit_opt = (*str == 't' || *str == 'T')
1016 ? PERL_ITHR_THREAD_EXIT_ONLY : 0;
1019 if (context == -1) {
1020 context = GIMME_V; /* Implicit context */
1022 context |= (GIMME_V & (~(G_ARRAY|G_SCALAR|G_VOID)));
1028 for (ii=2; ii < items ; ii++) {
1029 av_push(params, SvREFCNT_inc(ST(idx+ii)));
1034 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
1035 thread = S_ithread_create(aTHX_ function_to_call,
1039 newRV_noinc((SV*)params));
1041 XSRETURN_UNDEF; /* Mutex already unlocked */
1043 ST(0) = sv_2mortal(S_ithread_to_SV(aTHX_ Nullsv, thread, classname, FALSE));
1044 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
1046 /* Let thread run */
1047 MUTEX_UNLOCK(&thread->mutex);
1049 /* XSRETURN(1); - implied */
1059 int want_running = 0;
1063 /* Class method only */
1065 Perl_croak(aTHX_ "Usage: threads->list(...)");
1067 classname = (char *)SvPV_nolen(ST(0));
1069 /* Calling context */
1070 list_context = (GIMME_V == G_ARRAY);
1072 /* Running or joinable parameter */
1074 want_running = SvTRUE(ST(1));
1077 /* Walk through threads list */
1078 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
1079 for (thread = MY_POOL.main_thread.next;
1080 thread != &MY_POOL.main_thread;
1081 thread = thread->next)
1083 MUTEX_LOCK(&thread->mutex);
1084 state = thread->state;
1085 MUTEX_UNLOCK(&thread->mutex);
1087 /* Ignore detached or joined threads */
1088 if (state & PERL_ITHR_UNCALLABLE) {
1092 /* Filter per parameter */
1095 if (state & PERL_ITHR_FINISHED) {
1096 continue; /* Not running */
1099 if (! (state & PERL_ITHR_FINISHED)) {
1100 continue; /* Still running - not joinable yet */
1105 /* Push object on stack if list context */
1107 XPUSHs(sv_2mortal(S_ithread_to_SV(aTHX_ Nullsv, thread, classname, TRUE)));
1111 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
1112 /* If scalar context, send back count */
1113 if (! list_context) {
1124 /* Class method only */
1125 if ((items != 1) || SvROK(ST(0))) {
1126 Perl_croak(aTHX_ "Usage: threads->self()");
1128 classname = (char *)SvPV_nolen(ST(0));
1130 thread = S_ithread_get(aTHX);
1132 ST(0) = sv_2mortal(S_ithread_to_SV(aTHX_ Nullsv, thread, classname, TRUE));
1133 /* XSRETURN(1); - implied */
1141 PERL_UNUSED_VAR(items);
1142 thread = S_SV_to_ithread(aTHX_ ST(0));
1143 XST_mUV(0, thread->tid);
1144 /* XSRETURN(1); - implied */
1151 ithread *current_thread;
1162 /* Object method only */
1163 if ((items != 1) || ! sv_isobject(ST(0))) {
1164 Perl_croak(aTHX_ "Usage: $thr->join()");
1167 /* Check if the thread is joinable and not ourselves */
1168 thread = S_SV_to_ithread(aTHX_ ST(0));
1169 current_thread = S_ithread_get(aTHX);
1171 MUTEX_LOCK(&thread->mutex);
1172 if ((join_err = (thread->state & PERL_ITHR_UNCALLABLE))) {
1173 MUTEX_UNLOCK(&thread->mutex);
1174 Perl_croak(aTHX_ (join_err & PERL_ITHR_DETACHED)
1175 ? "Cannot join a detached thread"
1176 : "Thread already joined");
1177 } else if (thread->tid == current_thread->tid) {
1178 MUTEX_UNLOCK(&thread->mutex);
1179 Perl_croak(aTHX_ "Cannot join self");
1182 /* Mark as joined */
1183 thread->state |= PERL_ITHR_JOINED;
1184 MUTEX_UNLOCK(&thread->mutex);
1186 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
1187 MY_POOL.joinable_threads--;
1188 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
1190 /* Join the thread */
1192 if (WaitForSingleObject(thread->handle, INFINITE) != WAIT_OBJECT_0) {
1193 /* Timeout/abandonment unexpected here; check $^E */
1194 Perl_croak(aTHX_ "PANIC: underlying join failed");
1197 if ((rc_join = pthread_join(thread->thr, &retval)) != 0) {
1198 /* In progress/deadlock/unknown unexpected here; check $! */
1200 Perl_croak(aTHX_ "PANIC: underlying join failed");
1204 MUTEX_LOCK(&thread->mutex);
1205 /* Get the return value from the call_sv */
1206 /* Objects do not survive this process - FIXME */
1207 if ((thread->gimme & G_WANT) != G_VOID) {
1209 PerlInterpreter *other_perl;
1210 CLONE_PARAMS clone_params;
1212 params_copy = (AV *)SvRV(thread->params);
1213 other_perl = thread->interp;
1214 clone_params.stashes = newAV();
1215 clone_params.flags = CLONEf_JOIN_IN;
1216 PL_ptr_table = ptr_table_new();
1217 S_ithread_set(aTHX_ thread);
1218 /* Ensure 'meaningful' addresses retain their meaning */
1219 ptr_table_store(PL_ptr_table, &other_perl->Isv_undef, &PL_sv_undef);
1220 ptr_table_store(PL_ptr_table, &other_perl->Isv_no, &PL_sv_no);
1221 ptr_table_store(PL_ptr_table, &other_perl->Isv_yes, &PL_sv_yes);
1222 params = (AV *)sv_dup((SV*)params_copy, &clone_params);
1223 S_ithread_set(aTHX_ current_thread);
1224 SvREFCNT_dec(clone_params.stashes);
1225 SvREFCNT_inc_void(params);
1226 ptr_table_free(PL_ptr_table);
1227 PL_ptr_table = NULL;
1230 /* If thread didn't die, then we can free its interpreter */
1231 if (! (thread->state & PERL_ITHR_DIED)) {
1232 S_ithread_clear(aTHX_ thread);
1234 S_ithread_free(aTHX_ thread); /* Releases MUTEX */
1236 /* If no return values, then just return */
1241 /* Put return values on stack */
1242 len = (int)AvFILL(params);
1243 for (ii=0; ii <= len; ii++) {
1244 SV* param = av_shift(params);
1245 XPUSHs(sv_2mortal(param));
1248 /* Free return value array */
1249 SvREFCNT_dec(params);
1255 PERL_UNUSED_VAR(items);
1266 PERL_UNUSED_VAR(items);
1268 /* Detach the thread */
1269 thread = S_SV_to_ithread(aTHX_ ST(0));
1270 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
1271 MUTEX_LOCK(&thread->mutex);
1272 if (! (detach_err = (thread->state & PERL_ITHR_UNCALLABLE))) {
1273 /* Thread is detachable */
1274 thread->state |= PERL_ITHR_DETACHED;
1276 /* Windows has no 'detach thread' function */
1278 PERL_THREAD_DETACH(thread->thr);
1280 if (thread->state & PERL_ITHR_FINISHED) {
1281 MY_POOL.joinable_threads--;
1283 MY_POOL.running_threads--;
1284 MY_POOL.detached_threads++;
1287 MUTEX_UNLOCK(&thread->mutex);
1288 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
1291 Perl_croak(aTHX_ (detach_err & PERL_ITHR_DETACHED)
1292 ? "Thread already detached"
1293 : "Cannot detach a joined thread");
1296 /* If thread is finished and didn't die,
1297 * then we can free its interpreter */
1298 MUTEX_LOCK(&thread->mutex);
1299 if ((thread->state & PERL_ITHR_FINISHED) &&
1300 ! (thread->state & PERL_ITHR_DIED))
1302 S_ithread_clear(aTHX_ thread);
1304 S_ithread_free(aTHX_ thread); /* Releases MUTEX */
1314 /* Must have safe signals */
1315 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG) {
1316 Perl_croak(aTHX_ "Cannot signal threads without safe signals");
1319 /* Object method only */
1320 if ((items != 2) || ! sv_isobject(ST(0))) {
1321 Perl_croak(aTHX_ "Usage: $thr->kill('SIG...')");
1325 sig_name = SvPV_nolen(ST(1));
1326 if (isALPHA(*sig_name)) {
1327 if (*sig_name == 'S' && sig_name[1] == 'I' && sig_name[2] == 'G') {
1330 if ((signal = whichsig(sig_name)) < 0) {
1331 Perl_croak(aTHX_ "Unrecognized signal name: %s", sig_name);
1334 signal = SvIV(ST(1));
1337 /* Set the signal for the thread */
1338 thread = S_SV_to_ithread(aTHX_ ST(0));
1339 MUTEX_LOCK(&thread->mutex);
1340 if (thread->interp) {
1341 dTHXa(thread->interp);
1342 PL_psig_pend[signal]++;
1345 MUTEX_UNLOCK(&thread->mutex);
1347 /* Return the thread to allow for method chaining */
1349 /* XSRETURN(1); - implied */
1353 ithread_DESTROY(...)
1355 PERL_UNUSED_VAR(items);
1356 sv_unmagic(SvRV(ST(0)), PERL_MAGIC_shared_scalar);
1364 PERL_UNUSED_VAR(items);
1366 /* Compares TIDs to determine thread equality */
1367 if (sv_isobject(ST(0)) && sv_isobject(ST(1))) {
1368 ithread *thr1 = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1369 ithread *thr2 = INT2PTR(ithread *, SvIV(SvRV(ST(1))));
1370 are_equal = (thr1->tid == thr2->tid);
1375 /* Return 0 on false for backward compatibility */
1378 /* XSRETURN(1); - implied */
1391 /* Class method only */
1393 Perl_croak(aTHX_ "Usage: threads->object($tid)");
1395 classname = (char *)SvPV_nolen(ST(0));
1397 if ((items < 2) || ! SvOK(ST(1))) {
1401 /* threads->object($tid) */
1404 /* Walk through threads list */
1405 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
1406 for (thread = MY_POOL.main_thread.next;
1407 thread != &MY_POOL.main_thread;
1408 thread = thread->next)
1411 if (thread->tid == tid) {
1412 /* Ignore if detached or joined */
1413 MUTEX_LOCK(&thread->mutex);
1414 state = thread->state;
1415 MUTEX_UNLOCK(&thread->mutex);
1416 if (! (state & PERL_ITHR_UNCALLABLE)) {
1417 /* Put object on stack */
1418 ST(0) = sv_2mortal(S_ithread_to_SV(aTHX_ Nullsv, thread, classname, TRUE));
1424 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
1429 /* XSRETURN(1); - implied */
1433 ithread__handle(...);
1437 PERL_UNUSED_VAR(items);
1438 thread = S_SV_to_ithread(aTHX_ ST(0));
1440 XST_mUV(0, PTR2UV(&thread->handle));
1442 XST_mUV(0, PTR2UV(&thread->thr));
1444 /* XSRETURN(1); - implied */
1448 ithread_get_stack_size(...)
1453 PERL_UNUSED_VAR(items);
1454 if (sv_isobject(ST(0))) {
1455 /* $thr->get_stack_size() */
1456 ithread *thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1457 stack_size = thread->stack_size;
1459 /* threads->get_stack_size() */
1460 stack_size = MY_POOL.default_stack_size;
1462 XST_mIV(0, stack_size);
1463 /* XSRETURN(1); - implied */
1467 ithread_set_stack_size(...)
1473 Perl_croak(aTHX_ "Usage: threads->set_stack_size($size)");
1475 if (sv_isobject(ST(0))) {
1476 Perl_croak(aTHX_ "Cannot change stack size of an existing thread");
1478 if (! looks_like_number(ST(1))) {
1479 Perl_croak(aTHX_ "Stack size must be numeric");
1482 old_size = MY_POOL.default_stack_size;
1483 MY_POOL.default_stack_size = S_good_stack_size(aTHX_ SvIV(ST(1)));
1484 XST_mIV(0, old_size);
1485 /* XSRETURN(1); - implied */
1489 ithread_is_running(...)
1493 /* Object method only */
1494 if ((items != 1) || ! sv_isobject(ST(0))) {
1495 Perl_croak(aTHX_ "Usage: $thr->is_running()");
1498 thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1499 MUTEX_LOCK(&thread->mutex);
1500 ST(0) = (thread->state & PERL_ITHR_FINISHED) ? &PL_sv_no : &PL_sv_yes;
1501 MUTEX_UNLOCK(&thread->mutex);
1502 /* XSRETURN(1); - implied */
1506 ithread_is_detached(...)
1510 PERL_UNUSED_VAR(items);
1511 thread = S_SV_to_ithread(aTHX_ ST(0));
1512 MUTEX_LOCK(&thread->mutex);
1513 ST(0) = (thread->state & PERL_ITHR_DETACHED) ? &PL_sv_yes : &PL_sv_no;
1514 MUTEX_UNLOCK(&thread->mutex);
1515 /* XSRETURN(1); - implied */
1519 ithread_is_joinable(...)
1523 /* Object method only */
1524 if ((items != 1) || ! sv_isobject(ST(0))) {
1525 Perl_croak(aTHX_ "Usage: $thr->is_joinable()");
1528 thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1529 MUTEX_LOCK(&thread->mutex);
1530 ST(0) = ((thread->state & PERL_ITHR_FINISHED) &&
1531 ! (thread->state & PERL_ITHR_UNCALLABLE))
1532 ? &PL_sv_yes : &PL_sv_no;
1533 MUTEX_UNLOCK(&thread->mutex);
1534 /* XSRETURN(1); - implied */
1538 ithread_wantarray(...)
1542 PERL_UNUSED_VAR(items);
1543 thread = S_SV_to_ithread(aTHX_ ST(0));
1544 ST(0) = ((thread->gimme & G_WANT) == G_ARRAY) ? &PL_sv_yes :
1545 ((thread->gimme & G_WANT) == G_VOID) ? &PL_sv_undef
1546 /* G_SCALAR */ : &PL_sv_no;
1547 /* XSRETURN(1); - implied */
1551 ithread_set_thread_exit_only(...)
1556 Perl_croak(aTHX_ "Usage: ->set_thread_exit_only(boolean)");
1558 thread = S_SV_to_ithread(aTHX_ ST(0));
1559 MUTEX_LOCK(&thread->mutex);
1560 if (SvTRUE(ST(1))) {
1561 thread->state |= PERL_ITHR_THREAD_EXIT_ONLY;
1563 thread->state &= ~PERL_ITHR_THREAD_EXIT_ONLY;
1565 MUTEX_UNLOCK(&thread->mutex);
1574 /* Object method only */
1575 if ((items != 1) || ! sv_isobject(ST(0))) {
1576 Perl_croak(aTHX_ "Usage: $thr->err()");
1579 thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1580 MUTEX_LOCK(&thread->mutex);
1582 /* If thread died, then clone the error into the calling thread */
1583 if (thread->state & PERL_ITHR_DIED) {
1584 PerlInterpreter *other_perl;
1585 CLONE_PARAMS clone_params;
1586 ithread *current_thread;
1588 other_perl = thread->interp;
1589 clone_params.stashes = newAV();
1590 clone_params.flags = CLONEf_JOIN_IN;
1591 PL_ptr_table = ptr_table_new();
1592 current_thread = S_ithread_get(aTHX);
1593 S_ithread_set(aTHX_ thread);
1594 /* Ensure 'meaningful' addresses retain their meaning */
1595 ptr_table_store(PL_ptr_table, &other_perl->Isv_undef, &PL_sv_undef);
1596 ptr_table_store(PL_ptr_table, &other_perl->Isv_no, &PL_sv_no);
1597 ptr_table_store(PL_ptr_table, &other_perl->Isv_yes, &PL_sv_yes);
1598 err = sv_dup(thread->err, &clone_params);
1599 S_ithread_set(aTHX_ current_thread);
1600 SvREFCNT_dec(clone_params.stashes);
1601 SvREFCNT_inc_void(err);
1602 /* If error was an object, bless it into the correct class */
1603 if (thread->err_class) {
1604 sv_bless(err, gv_stashpv(thread->err_class, 1));
1606 ptr_table_free(PL_ptr_table);
1607 PL_ptr_table = NULL;
1610 MUTEX_UNLOCK(&thread->mutex);
1616 ST(0) = sv_2mortal(err);
1617 /* XSRETURN(1); - implied */
1620 #endif /* USE_ITHREADS */
1626 SV *my_pool_sv = *hv_fetch(PL_modglobal, MY_POOL_KEY,
1627 sizeof(MY_POOL_KEY)-1, TRUE);
1628 my_pool_t *my_poolp = (my_pool_t*)SvPVX(newSV(sizeof(my_pool_t)-1));
1632 Zero(my_poolp, 1, my_pool_t);
1633 sv_setuv(my_pool_sv, PTR2UV(my_poolp));
1635 PL_perl_destruct_level = 2;
1636 MUTEX_INIT(&MY_POOL.create_destruct_mutex);
1637 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
1639 PL_threadhook = &Perl_ithread_hook;
1641 MY_POOL.tid_counter = 1;
1642 # ifdef THREAD_CREATE_NEEDS_STACK
1643 MY_POOL.default_stack_size = THREAD_CREATE_NEEDS_STACK;
1646 /* The 'main' thread is thread 0.
1647 * It is detached (unjoinable) and immortal.
1650 MUTEX_INIT(&MY_POOL.main_thread.mutex);
1652 /* Head of the threads list */
1653 MY_POOL.main_thread.next = &MY_POOL.main_thread;
1654 MY_POOL.main_thread.prev = &MY_POOL.main_thread;
1656 MY_POOL.main_thread.count = 1; /* Immortal */
1658 MY_POOL.main_thread.interp = aTHX;
1659 MY_POOL.main_thread.state = PERL_ITHR_DETACHED; /* Detached */
1660 MY_POOL.main_thread.stack_size = MY_POOL.default_stack_size;
1662 MY_POOL.main_thread.thr = GetCurrentThreadId();
1664 MY_POOL.main_thread.thr = pthread_self();
1667 S_ithread_set(aTHX_ &MY_POOL.main_thread);
1668 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
1669 #endif /* USE_ITHREADS */