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_nolen
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 */
81 #define MY_CXT_KEY "threads::_cxt" XS_VERSION
84 /* Used by Perl interpreter for thread context switching */
91 #define MY_POOL_KEY "threads::_pool" XS_VERSION
94 /* Structure for 'main' thread
95 * Also forms the 'base' for the doubly-linked list of threads */
98 /* Protects the creation and destruction of threads*/
99 perl_mutex create_destruct_mutex;
106 IV default_stack_size;
111 SV *my_pool_sv = *hv_fetch(PL_modglobal, MY_POOL_KEY, \
112 sizeof(MY_POOL_KEY)-1, TRUE); \
113 my_pool_t *my_poolp = INT2PTR(my_pool_t*, SvUV(my_pool_sv))
115 #define MY_POOL (*my_poolp)
118 /* Used by Perl interpreter for thread context switching */
120 S_ithread_set(pTHX_ ithread *thread)
123 MY_CXT.context = thread;
130 return (MY_CXT.context);
134 /* Free any data (such as the Perl interpreter) attached to an ithread
135 * structure. This is a bit like undef on SVs, where the SV isn't freed,
136 * but the PVX is. Must be called with thread->mutex already held.
139 S_ithread_clear(pTHX_ ithread *thread)
141 PerlInterpreter *interp;
143 assert(((thread->state & PERL_ITHR_FINISHED) &&
144 (thread->state & PERL_ITHR_UNCALLABLE))
146 (thread->state & PERL_ITHR_NONVIABLE));
148 interp = thread->interp;
152 PERL_SET_CONTEXT(interp);
153 S_ithread_set(aTHX_ thread);
155 SvREFCNT_dec(thread->params);
156 thread->params = Nullsv;
159 SvREFCNT_dec(thread->err);
160 thread->err = Nullsv;
163 perl_destruct(interp);
165 thread->interp = NULL;
168 PERL_SET_CONTEXT(aTHX);
172 /* Decrement the refcount of an ithread, and if it reaches zero, free it.
173 * Must be called with the mutex held.
174 * On return, mutex is released (or destroyed) */
177 S_ithread_free(pTHX_ ithread *thread)
184 if (! (thread->state & PERL_ITHR_NONVIABLE)) {
185 assert(thread->count > 0);
186 if (--thread->count > 0) {
187 MUTEX_UNLOCK(&thread->mutex);
190 assert((thread->state & PERL_ITHR_FINISHED)
191 && (thread->state & PERL_ITHR_UNCALLABLE));
193 MUTEX_UNLOCK(&thread->mutex);
195 /* Main thread (0) is immortal and should never get here */
196 assert(thread->tid != 0);
198 /* Remove from circular list of threads */
199 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
200 assert(thread->prev && thread->next);
201 thread->next->prev = thread->prev;
202 thread->prev->next = thread->next;
206 /* after decrementing this thread count and unlocking the MUTEX, this
207 * thread must not make any further use of MY_POOL, as it may be freed
209 MY_POOL.total_threads--;
210 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
212 /* Thread is now disowned */
213 MUTEX_LOCK(&thread->mutex);
214 S_ithread_clear(aTHX_ thread);
217 handle = thread->handle;
218 thread->handle = NULL;
220 MUTEX_UNLOCK(&thread->mutex);
221 MUTEX_DESTROY(&thread->mutex);
229 /* Call PerlMemShared_free() in the context of the "first" interpreter
230 * per http://www.nntp.perl.org/group/perl.perl5.porters/110772
232 aTHX = MY_POOL.main_thread.interp;
233 PerlMemShared_free(thread);
239 S_ithread_count_inc(pTHX_ ithread *thread)
241 MUTEX_LOCK(&thread->mutex);
243 MUTEX_UNLOCK(&thread->mutex);
248 /* Warn if exiting with any unjoined threads */
252 int veto_cleanup, warn;
255 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
256 veto_cleanup = (MY_POOL.total_threads > 0);
257 warn = (MY_POOL.running_threads || MY_POOL.joinable_threads);
258 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
261 if (ckWARN_d(WARN_THREADS)) {
262 Perl_warn(aTHX_ "Perl exited with active threads:\n\t%"
263 IVdf " running and unjoined\n\t%"
264 IVdf " finished and unjoined\n\t%"
265 IVdf " running and detached\n",
266 MY_POOL.running_threads,
267 MY_POOL.joinable_threads,
268 MY_POOL.detached_threads);
272 return (veto_cleanup);
275 /* Called on exit from main thread */
277 Perl_ithread_hook(pTHX)
280 return ((aTHX == MY_POOL.main_thread.interp) ? S_exit_warning(aTHX) : 0);
284 /* MAGIC (in mg.h sense) hooks */
287 ithread_mg_get(pTHX_ SV *sv, MAGIC *mg)
289 ithread *thread = (ithread *)mg->mg_ptr;
290 SvIV_set(sv, PTR2IV(thread));
296 ithread_mg_free(pTHX_ SV *sv, MAGIC *mg)
298 ithread *thread = (ithread *)mg->mg_ptr;
299 MUTEX_LOCK(&thread->mutex);
300 S_ithread_free(aTHX_ thread); /* releases MUTEX */
306 ithread_mg_dup(pTHX_ MAGIC *mg, CLONE_PARAMS *param)
308 S_ithread_count_inc(aTHX_ (ithread *)mg->mg_ptr);
312 MGVTBL ithread_vtbl = {
313 ithread_mg_get, /* get */
317 ithread_mg_free, /* free */
319 ithread_mg_dup /* dup */
323 /* Provided default, minimum and rational stack sizes */
325 S_good_stack_size(pTHX_ IV stack_size)
329 /* Use default stack size if no stack size specified */
331 return (MY_POOL.default_stack_size);
334 #ifdef PTHREAD_STACK_MIN
335 /* Can't use less than minimum */
336 if (stack_size < PTHREAD_STACK_MIN) {
337 if (ckWARN(WARN_THREADS)) {
338 Perl_warn(aTHX_ "Using minimum thread stack size of %" IVdf, (IV)PTHREAD_STACK_MIN);
340 return (PTHREAD_STACK_MIN);
344 /* Round up to page size boundary */
345 if (MY_POOL.page_size <= 0) {
346 #if defined(HAS_SYSCONF) && (defined(_SC_PAGESIZE) || defined(_SC_MMAP_PAGE_SIZE))
347 SETERRNO(0, SS_NORMAL);
349 MY_POOL.page_size = sysconf(_SC_PAGESIZE);
351 MY_POOL.page_size = sysconf(_SC_MMAP_PAGE_SIZE);
353 if ((long)MY_POOL.page_size < 0) {
355 SV * const error = get_sv("@", FALSE);
356 (void)SvUPGRADE(error, SVt_PV);
357 Perl_croak(aTHX_ "PANIC: sysconf: %s", SvPV_nolen(error));
359 Perl_croak(aTHX_ "PANIC: sysconf: pagesize unknown");
363 # ifdef HAS_GETPAGESIZE
364 MY_POOL.page_size = getpagesize();
366 # if defined(I_SYS_PARAM) && defined(PAGESIZE)
367 MY_POOL.page_size = PAGESIZE;
369 MY_POOL.page_size = 8192; /* A conservative default */
372 if (MY_POOL.page_size <= 0) {
373 Perl_croak(aTHX_ "PANIC: bad pagesize %" IVdf, (IV)MY_POOL.page_size);
377 stack_size = ((stack_size + (MY_POOL.page_size - 1)) / MY_POOL.page_size) * MY_POOL.page_size;
383 /* Starts executing the thread.
384 * Passed as the C level function to run in the new thread.
387 STATIC THREAD_RET_TYPE
388 S_ithread_run(LPVOID arg)
391 S_ithread_run(void * arg)
394 ithread *thread = (ithread *)arg;
397 int exit_app = 0; /* Thread terminated using 'exit' */
399 int died = 0; /* Thread terminated abnormally */
403 dTHXa(thread->interp);
407 /* Blocked until ->create() call finishes */
408 MUTEX_LOCK(&thread->mutex);
409 MUTEX_UNLOCK(&thread->mutex);
411 PERL_SET_CONTEXT(thread->interp);
412 S_ithread_set(aTHX_ thread);
414 PL_perl_destruct_level = 2;
417 AV *params = (AV *)SvRV(thread->params);
418 int len = (int)av_len(params)+1;
425 /* Put args on the stack */
427 for (ii=0; ii < len; ii++) {
428 XPUSHs(av_shift(params));
432 oldscope = PL_scopestack_ix;
435 /* Run the specified function */
436 len = (int)call_sv(thread->init_function, thread->gimme|G_EVAL);
437 } else if (jmp_rc == 2) {
440 exit_code = STATUS_CURRENT;
441 while (PL_scopestack_ix > oldscope) {
447 /* Remove args from stack and put back in params array */
449 for (ii=len-1; ii >= 0; ii--) {
452 av_store(params, ii, SvREFCNT_inc(sv));
459 /* Check for abnormal termination */
461 died = PERL_ITHR_DIED;
462 thread->err = newSVsv(ERRSV);
463 /* If ERRSV is an object, remember the classname and then
464 * rebless into 'main' so it will survive 'cloning'
466 if (sv_isobject(thread->err)) {
467 thread->err_class = HvNAME(SvSTASH(SvRV(thread->err)));
468 sv_bless(thread->err, gv_stashpv("main", 0));
471 if (ckWARN_d(WARN_THREADS)) {
472 oldscope = PL_scopestack_ix;
475 /* Warn that thread died */
476 Perl_warn(aTHX_ "Thread %" UVuf " terminated abnormally: %" SVf, thread->tid, ERRSV);
477 } else if (jmp_rc == 2) {
478 /* Warn handler exited */
480 exit_code = STATUS_CURRENT;
481 while (PL_scopestack_ix > oldscope) {
489 /* Release function ref */
490 SvREFCNT_dec(thread->init_function);
491 thread->init_function = Nullsv;
494 PerlIO_flush((PerlIO *)NULL);
496 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
497 MUTEX_LOCK(&thread->mutex);
498 /* Mark as finished */
499 thread->state |= (PERL_ITHR_FINISHED | died);
500 /* Clear exit flag if required */
501 if (thread->state & PERL_ITHR_THREAD_EXIT_ONLY) {
505 /* Adjust thread status counts */
506 if (thread->state & PERL_ITHR_DETACHED) {
507 MY_POOL.detached_threads--;
509 MY_POOL.running_threads--;
510 MY_POOL.joinable_threads++;
512 MUTEX_UNLOCK(&thread->mutex);
513 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
515 /* Exit application if required */
517 oldscope = PL_scopestack_ix;
520 /* Warn if there are unjoined threads */
521 S_exit_warning(aTHX);
522 } else if (jmp_rc == 2) {
523 /* Warn handler exited */
524 exit_code = STATUS_CURRENT;
525 while (PL_scopestack_ix > oldscope) {
534 MUTEX_LOCK(&thread->mutex);
535 S_ithread_free(aTHX_ thread); /* releases MUTEX */
545 /* Type conversion helper functions */
548 S_ithread_to_SV(pTHX_ SV *obj, ithread *thread, char *classname, bool inc)
554 S_ithread_count_inc(aTHX_ thread);
560 sv = newSVrv(obj, classname);
561 sv_setiv(sv, PTR2IV(thread));
562 mg = sv_magicext(sv, Nullsv, PERL_MAGIC_shared_scalar, &ithread_vtbl, (char *)thread, 0);
563 mg->mg_flags |= MGf_DUP;
570 S_SV_to_ithread(pTHX_ SV *sv)
572 /* Argument is a thread */
574 return (INT2PTR(ithread *, SvIV(SvRV(sv))));
576 /* Argument is classname, therefore return current thread */
577 return (S_ithread_get(aTHX));
582 * Called in context of parent thread.
583 * Called with MY_POOL.create_destruct_mutex locked. (Unlocked on error.)
587 pTHX_ SV *init_function,
594 ithread *current_thread = S_ithread_get(aTHX);
596 SV **tmps_tmp = PL_tmps_stack;
597 IV tmps_ix = PL_tmps_ix;
599 int rc_stack_size = 0;
600 int rc_thread_create = 0;
604 /* Allocate thread structure in context of the main thread's interpreter */
606 PERL_SET_CONTEXT(MY_POOL.main_thread.interp);
607 thread = (ithread *)PerlMemShared_malloc(sizeof(ithread));
609 PERL_SET_CONTEXT(aTHX);
611 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
612 PerlLIO_write(PerlIO_fileno(Perl_error_log), PL_no_mem, strlen(PL_no_mem));
615 Zero(thread, 1, ithread);
617 /* Add to threads list */
618 thread->next = &MY_POOL.main_thread;
619 thread->prev = MY_POOL.main_thread.prev;
620 MY_POOL.main_thread.prev = thread;
621 thread->prev->next = thread;
622 MY_POOL.total_threads++;
624 /* 1 ref to be held by the local var 'thread' in S_ithread_run()
625 * 1 ref to be held by the threads object that we assume we will
626 * be embedded in upon our return
627 * 1 ref to be the responsibility of join/detach, so we don't get freed
628 until join/detach, even if no thread objects remain. This
629 allows the following to work:
630 { threads->new(sub{...}); } threads->object(1)->join;
634 /* Block new thread until ->create() call finishes */
635 MUTEX_INIT(&thread->mutex);
636 MUTEX_LOCK(&thread->mutex);
638 thread->tid = MY_POOL.tid_counter++;
639 thread->stack_size = S_good_stack_size(aTHX_ stack_size);
640 thread->gimme = gimme;
641 thread->state = exit_opt;
643 /* "Clone" our interpreter into the thread's interpreter.
644 * This gives thread access to "static data" and code.
646 PerlIO_flush((PerlIO *)NULL);
647 S_ithread_set(aTHX_ thread);
649 SAVEBOOL(PL_srand_called); /* Save this so it becomes the correct value */
650 PL_srand_called = FALSE; /* Set it to false so we can detect if it gets
651 set during the clone */
654 thread->interp = perl_clone(aTHX, CLONEf_KEEP_PTR_TABLE | CLONEf_CLONE_HOST);
656 thread->interp = perl_clone(aTHX, CLONEf_KEEP_PTR_TABLE);
659 /* perl_clone() leaves us in new interpreter's context. As it is tricky
660 * to spot an implicit aTHX, create a new scope with aTHX matching the
661 * context for the duration of our work for new interpreter.
664 CLONE_PARAMS clone_param;
666 dTHXa(thread->interp);
670 /* Here we remove END blocks since they should only run in the thread
673 SvREFCNT_dec(PL_endav);
676 clone_param.flags = 0;
677 if (SvPOK(init_function)) {
678 thread->init_function = newSV(0);
679 sv_copypv(thread->init_function, init_function);
681 thread->init_function = sv_dup(init_function, &clone_param);
682 if (SvREFCNT(thread->init_function) == 0) {
683 SvREFCNT_inc_void(thread->init_function);
687 thread->params = sv_dup(params, &clone_param);
688 SvREFCNT_inc_void(thread->params);
690 /* The code below checks that anything living on the tmps stack and
691 * has been cloned (so it lives in the ptr_table) has a refcount
694 * If the refcount is 0 it means that a something on the stack/context
695 * was holding a reference to it and since we init_stacks() in
696 * perl_clone that won't get cleaned and we will get a leaked scalar.
697 * The reason it was cloned was that it lived on the @_ stack.
699 * Example of this can be found in bugreport 15837 where calls in the
700 * parameter list end up as a temp.
702 * One could argue that this fix should be in perl_clone.
704 while (tmps_ix > 0) {
705 SV* sv = (SV*)ptr_table_fetch(PL_ptr_table, tmps_tmp[tmps_ix]);
707 if (sv && SvREFCNT(sv) == 0) {
708 SvREFCNT_inc_void(sv);
713 SvTEMP_off(thread->init_function);
714 ptr_table_free(PL_ptr_table);
716 PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
718 S_ithread_set(aTHX_ current_thread);
719 PERL_SET_CONTEXT(aTHX);
721 /* Create/start the thread */
723 thread->handle = CreateThread(NULL,
724 (DWORD)thread->stack_size,
727 STACK_SIZE_PARAM_IS_A_RESERVATION,
731 STATIC pthread_attr_t attr;
732 STATIC int attr_inited = 0;
733 STATIC int attr_joinable = PTHREAD_CREATE_JOINABLE;
735 pthread_attr_init(&attr);
739 # ifdef PTHREAD_ATTR_SETDETACHSTATE
740 /* Threads start out joinable */
741 PTHREAD_ATTR_SETDETACHSTATE(&attr, attr_joinable);
744 # ifdef _POSIX_THREAD_ATTR_STACKSIZE
745 /* Set thread's stack size */
746 if (thread->stack_size > 0) {
747 rc_stack_size = pthread_attr_setstacksize(&attr, (size_t)thread->stack_size);
751 /* Create the thread */
752 if (! rc_stack_size) {
753 # ifdef OLD_PTHREADS_API
754 rc_thread_create = pthread_create(&thread->thr,
759 # if defined(HAS_PTHREAD_ATTR_SETSCOPE) && defined(PTHREAD_SCOPE_SYSTEM)
760 pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);
762 rc_thread_create = pthread_create(&thread->thr,
769 # ifdef _POSIX_THREAD_ATTR_STACKSIZE
770 /* Try to get thread's actual stack size */
774 stacksize = pthread_attr_getstacksize(attr);
776 if (! pthread_attr_getstacksize(&attr, &stacksize))
779 thread->stack_size = (IV)stacksize;
786 /* Check for errors */
788 if (thread->handle == NULL) {
790 if (rc_stack_size || rc_thread_create) {
792 /* Must unlock mutex for destruct call */
793 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
795 thread->state |= PERL_ITHR_NONVIABLE;
796 S_ithread_free(aTHX_ thread); /* releases MUTEX */
798 if (ckWARN_d(WARN_THREADS)) {
800 Perl_warn(aTHX_ "Thread creation failed: pthread_attr_setstacksize(%" IVdf ") returned %d", thread->stack_size, rc_stack_size);
802 Perl_warn(aTHX_ "Thread creation failed: pthread_create returned %d", rc_thread_create);
809 MY_POOL.running_threads++;
814 #endif /* USE_ITHREADS */
817 MODULE = threads PACKAGE = threads PREFIX = ithread_
827 SV *function_to_call;
833 SV *thread_exit_only;
839 if ((items >= 2) && SvROK(ST(1)) && SvTYPE(SvRV(ST(1)))==SVt_PVHV) {
841 Perl_croak(aTHX_ "Usage: threads->create(\\%specs, function, ...)");
843 specs = (HV*)SvRV(ST(1));
847 Perl_croak(aTHX_ "Usage: threads->create(function, ...)");
853 if (sv_isobject(ST(0))) {
855 classname = HvNAME(SvSTASH(SvRV(ST(0))));
856 thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
857 MUTEX_LOCK(&thread->mutex);
858 stack_size = thread->stack_size;
859 exit_opt = thread->state & PERL_ITHR_THREAD_EXIT_ONLY;
860 MUTEX_UNLOCK(&thread->mutex);
862 /* threads->create() */
863 classname = (char *)SvPV_nolen(ST(0));
864 stack_size = MY_POOL.default_stack_size;
865 thread_exit_only = get_sv("threads::thread_exit_only", TRUE);
866 exit_opt = (SvTRUE(thread_exit_only))
867 ? PERL_ITHR_THREAD_EXIT_ONLY : 0;
870 function_to_call = ST(idx+1);
875 if (hv_exists(specs, "stack", 5)) {
876 stack_size = SvIV(*hv_fetch(specs, "stack", 5, 0));
877 } else if (hv_exists(specs, "stacksize", 9)) {
878 stack_size = SvIV(*hv_fetch(specs, "stacksize", 9, 0));
879 } else if (hv_exists(specs, "stack_size", 10)) {
880 stack_size = SvIV(*hv_fetch(specs, "stack_size", 10, 0));
884 if (hv_exists(specs, "context", 7)) {
885 str = (char *)SvPV_nolen(*hv_fetch(specs, "context", 7, 0));
900 Perl_croak(aTHX_ "Invalid context: %s", str);
902 } else if (hv_exists(specs, "array", 5)) {
903 if (SvTRUE(*hv_fetch(specs, "array", 5, 0))) {
906 } else if (hv_exists(specs, "scalar", 6)) {
907 if (SvTRUE(*hv_fetch(specs, "scalar", 6, 0))) {
910 } else if (hv_exists(specs, "void", 4)) {
911 if (SvTRUE(*hv_fetch(specs, "void", 4, 0))) {
916 /* exit => thread_only */
917 if (hv_exists(specs, "exit", 4)) {
918 str = (char *)SvPV_nolen(*hv_fetch(specs, "exit", 4, 0));
919 exit_opt = (*str == 't' || *str == 'T')
920 ? PERL_ITHR_THREAD_EXIT_ONLY : 0;
924 context = GIMME_V; /* Implicit context */
926 context |= (GIMME_V & (~(G_ARRAY|G_SCALAR|G_VOID)));
932 for (ii=2; ii < items ; ii++) {
933 av_push(params, SvREFCNT_inc(ST(idx+ii)));
938 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
939 thread = S_ithread_create(aTHX_ function_to_call,
943 newRV_noinc((SV*)params));
945 XSRETURN_UNDEF; /* Mutex already unlocked */
947 ST(0) = sv_2mortal(S_ithread_to_SV(aTHX_ Nullsv, thread, classname, FALSE));
948 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
951 MUTEX_UNLOCK(&thread->mutex);
953 /* XSRETURN(1); - implied */
963 int want_running = 0;
967 /* Class method only */
969 Perl_croak(aTHX_ "Usage: threads->list(...)");
971 classname = (char *)SvPV_nolen(ST(0));
973 /* Calling context */
974 list_context = (GIMME_V == G_ARRAY);
976 /* Running or joinable parameter */
978 want_running = SvTRUE(ST(1));
981 /* Walk through threads list */
982 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
983 for (thread = MY_POOL.main_thread.next;
984 thread != &MY_POOL.main_thread;
985 thread = thread->next)
987 MUTEX_LOCK(&thread->mutex);
988 state = thread->state;
989 MUTEX_UNLOCK(&thread->mutex);
991 /* Ignore detached or joined threads */
992 if (state & PERL_ITHR_UNCALLABLE) {
996 /* Filter per parameter */
999 if (state & PERL_ITHR_FINISHED) {
1000 continue; /* Not running */
1003 if (! (state & PERL_ITHR_FINISHED)) {
1004 continue; /* Still running - not joinable yet */
1009 /* Push object on stack if list context */
1011 XPUSHs(sv_2mortal(S_ithread_to_SV(aTHX_ Nullsv, thread, classname, TRUE)));
1015 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
1016 /* If scalar context, send back count */
1017 if (! list_context) {
1028 /* Class method only */
1029 if ((items != 1) || SvROK(ST(0))) {
1030 Perl_croak(aTHX_ "Usage: threads->self()");
1032 classname = (char *)SvPV_nolen(ST(0));
1034 thread = S_ithread_get(aTHX);
1036 ST(0) = sv_2mortal(S_ithread_to_SV(aTHX_ Nullsv, thread, classname, TRUE));
1037 /* XSRETURN(1); - implied */
1045 PERL_UNUSED_VAR(items);
1046 thread = S_SV_to_ithread(aTHX_ ST(0));
1047 XST_mUV(0, thread->tid);
1048 /* XSRETURN(1); - implied */
1055 ithread *current_thread;
1068 /* Object method only */
1069 if ((items != 1) || ! sv_isobject(ST(0))) {
1070 Perl_croak(aTHX_ "Usage: $thr->join()");
1073 /* Check if the thread is joinable and not ourselves */
1074 thread = S_SV_to_ithread(aTHX_ ST(0));
1075 current_thread = S_ithread_get(aTHX);
1077 MUTEX_LOCK(&thread->mutex);
1078 if ((join_err = (thread->state & PERL_ITHR_UNCALLABLE))) {
1079 MUTEX_UNLOCK(&thread->mutex);
1080 Perl_croak(aTHX_ (join_err & PERL_ITHR_DETACHED)
1081 ? "Cannot join a detached thread"
1082 : "Thread already joined");
1083 } else if (thread->tid == current_thread->tid) {
1084 MUTEX_UNLOCK(&thread->mutex);
1085 Perl_croak(aTHX_ "Cannot join self");
1088 /* Mark as joined */
1089 thread->state |= PERL_ITHR_JOINED;
1090 MUTEX_UNLOCK(&thread->mutex);
1092 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
1093 MY_POOL.joinable_threads--;
1094 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
1096 /* Join the thread */
1098 if (WaitForSingleObject(thread->handle, INFINITE) != WAIT_OBJECT_0) {
1099 /* Timeout/abandonment unexpected here; check $^E */
1100 Perl_croak(aTHX_ "PANIC: underlying join failed");
1103 if ((rc_join = pthread_join(thread->thr, &retval)) != 0) {
1104 /* In progress/deadlock/unknown unexpected here; check $! */
1106 Perl_croak(aTHX_ "PANIC: underlying join failed");
1110 MUTEX_LOCK(&thread->mutex);
1111 /* Get the return value from the call_sv */
1112 /* Objects do not survive this process - FIXME */
1115 PerlInterpreter *other_perl;
1116 CLONE_PARAMS clone_params;
1118 params_copy = (AV *)SvRV(thread->params);
1119 other_perl = thread->interp;
1120 clone_params.stashes = newAV();
1121 clone_params.flags = CLONEf_JOIN_IN;
1122 PL_ptr_table = ptr_table_new();
1123 S_ithread_set(aTHX_ thread);
1124 /* Ensure 'meaningful' addresses retain their meaning */
1125 ptr_table_store(PL_ptr_table, &other_perl->Isv_undef, &PL_sv_undef);
1126 ptr_table_store(PL_ptr_table, &other_perl->Isv_no, &PL_sv_no);
1127 ptr_table_store(PL_ptr_table, &other_perl->Isv_yes, &PL_sv_yes);
1128 params = (AV *)sv_dup((SV*)params_copy, &clone_params);
1129 S_ithread_set(aTHX_ current_thread);
1130 SvREFCNT_dec(clone_params.stashes);
1131 SvREFCNT_inc_void(params);
1132 ptr_table_free(PL_ptr_table);
1133 PL_ptr_table = NULL;
1136 /* If thread didn't die, then we can free its interpreter */
1137 if (! (thread->state & PERL_ITHR_DIED)) {
1138 S_ithread_clear(aTHX_ thread);
1140 S_ithread_free(aTHX_ thread); /* releases MUTEX */
1142 /* If no return values, then just return */
1147 /* Put return values on stack */
1148 len = (int)AvFILL(params);
1149 for (ii=0; ii <= len; ii++) {
1150 SV* param = av_shift(params);
1151 XPUSHs(sv_2mortal(param));
1154 /* Free return value array */
1155 SvREFCNT_dec(params);
1161 PERL_UNUSED_VAR(items);
1172 PERL_UNUSED_VAR(items);
1174 /* Detach the thread */
1175 thread = S_SV_to_ithread(aTHX_ ST(0));
1176 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
1177 MUTEX_LOCK(&thread->mutex);
1178 if (! (detach_err = (thread->state & PERL_ITHR_UNCALLABLE))) {
1179 /* Thread is detachable */
1180 thread->state |= PERL_ITHR_DETACHED;
1182 /* Windows has no 'detach thread' function */
1184 PERL_THREAD_DETACH(thread->thr);
1186 if (thread->state & PERL_ITHR_FINISHED) {
1187 MY_POOL.joinable_threads--;
1189 MY_POOL.running_threads--;
1190 MY_POOL.detached_threads++;
1193 MUTEX_UNLOCK(&thread->mutex);
1194 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
1197 Perl_croak(aTHX_ (detach_err & PERL_ITHR_DETACHED)
1198 ? "Thread already detached"
1199 : "Cannot detach a joined thread");
1202 /* If thread is finished and didn't die,
1203 * then we can free its interpreter */
1204 MUTEX_LOCK(&thread->mutex);
1205 if ((thread->state & PERL_ITHR_FINISHED) &&
1206 ! (thread->state & PERL_ITHR_DIED))
1208 S_ithread_clear(aTHX_ thread);
1210 S_ithread_free(aTHX_ thread); /* releases MUTEX */
1221 /* Must have safe signals */
1222 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG) {
1223 Perl_croak(aTHX_ "Cannot signal threads without safe signals");
1226 /* Object method only */
1227 if ((items != 2) || ! sv_isobject(ST(0))) {
1228 Perl_croak(aTHX_ "Usage: $thr->kill('SIG...')");
1232 sig_name = SvPV_nolen(ST(1));
1233 if (isALPHA(*sig_name)) {
1234 if (*sig_name == 'S' && sig_name[1] == 'I' && sig_name[2] == 'G') {
1237 if ((signal = whichsig(sig_name)) < 0) {
1238 Perl_croak(aTHX_ "Unrecognized signal name: %s", sig_name);
1241 signal = SvIV(ST(1));
1244 /* Set the signal for the thread */
1245 thread = S_SV_to_ithread(aTHX_ ST(0));
1246 MUTEX_LOCK(&thread->mutex);
1247 if (thread->interp) {
1248 dTHXa(thread->interp);
1249 PL_psig_pend[signal]++;
1252 MUTEX_UNLOCK(&thread->mutex);
1254 /* Return the thread to allow for method chaining */
1256 /* XSRETURN(1); - implied */
1260 ithread_DESTROY(...)
1262 PERL_UNUSED_VAR(items);
1263 sv_unmagic(SvRV(ST(0)), PERL_MAGIC_shared_scalar);
1271 PERL_UNUSED_VAR(items);
1273 /* Compares TIDs to determine thread equality */
1274 if (sv_isobject(ST(0)) && sv_isobject(ST(1))) {
1275 ithread *thr1 = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1276 ithread *thr2 = INT2PTR(ithread *, SvIV(SvRV(ST(1))));
1277 are_equal = (thr1->tid == thr2->tid);
1282 /* Return 0 on false for backward compatibility */
1285 /* XSRETURN(1); - implied */
1298 /* Class method only */
1300 Perl_croak(aTHX_ "Usage: threads->object($tid)");
1302 classname = (char *)SvPV_nolen(ST(0));
1304 if ((items < 2) || ! SvOK(ST(1))) {
1308 /* threads->object($tid) */
1311 /* Walk through threads list */
1312 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
1313 for (thread = MY_POOL.main_thread.next;
1314 thread != &MY_POOL.main_thread;
1315 thread = thread->next)
1318 if (thread->tid == tid) {
1319 /* Ignore if detached or joined */
1320 MUTEX_LOCK(&thread->mutex);
1321 state = thread->state;
1322 MUTEX_UNLOCK(&thread->mutex);
1323 if (! (state & PERL_ITHR_UNCALLABLE)) {
1324 /* Put object on stack */
1325 ST(0) = sv_2mortal(S_ithread_to_SV(aTHX_ Nullsv, thread, classname, TRUE));
1331 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
1336 /* XSRETURN(1); - implied */
1340 ithread__handle(...);
1344 PERL_UNUSED_VAR(items);
1345 thread = S_SV_to_ithread(aTHX_ ST(0));
1347 XST_mUV(0, PTR2UV(&thread->handle));
1349 XST_mUV(0, PTR2UV(&thread->thr));
1351 /* XSRETURN(1); - implied */
1355 ithread_get_stack_size(...)
1360 PERL_UNUSED_VAR(items);
1361 if (sv_isobject(ST(0))) {
1362 /* $thr->get_stack_size() */
1363 ithread *thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1364 stack_size = thread->stack_size;
1366 /* threads->get_stack_size() */
1367 stack_size = MY_POOL.default_stack_size;
1369 XST_mIV(0, stack_size);
1370 /* XSRETURN(1); - implied */
1374 ithread_set_stack_size(...)
1380 Perl_croak(aTHX_ "Usage: threads->set_stack_size($size)");
1382 if (sv_isobject(ST(0))) {
1383 Perl_croak(aTHX_ "Cannot change stack size of an existing thread");
1386 old_size = MY_POOL.default_stack_size;
1387 MY_POOL.default_stack_size = S_good_stack_size(aTHX_ SvIV(ST(1)));
1388 XST_mIV(0, old_size);
1389 /* XSRETURN(1); - implied */
1393 ithread_is_running(...)
1397 /* Object method only */
1398 if ((items != 1) || ! sv_isobject(ST(0))) {
1399 Perl_croak(aTHX_ "Usage: $thr->is_running()");
1402 thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1403 MUTEX_LOCK(&thread->mutex);
1404 ST(0) = (thread->state & PERL_ITHR_FINISHED) ? &PL_sv_no : &PL_sv_yes;
1405 MUTEX_UNLOCK(&thread->mutex);
1406 /* XSRETURN(1); - implied */
1410 ithread_is_detached(...)
1414 PERL_UNUSED_VAR(items);
1415 thread = S_SV_to_ithread(aTHX_ ST(0));
1416 MUTEX_LOCK(&thread->mutex);
1417 ST(0) = (thread->state & PERL_ITHR_DETACHED) ? &PL_sv_yes : &PL_sv_no;
1418 MUTEX_UNLOCK(&thread->mutex);
1419 /* XSRETURN(1); - implied */
1423 ithread_is_joinable(...)
1427 /* Object method only */
1428 if ((items != 1) || ! sv_isobject(ST(0))) {
1429 Perl_croak(aTHX_ "Usage: $thr->is_joinable()");
1432 thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1433 MUTEX_LOCK(&thread->mutex);
1434 ST(0) = ((thread->state & PERL_ITHR_FINISHED) &&
1435 ! (thread->state & PERL_ITHR_UNCALLABLE))
1436 ? &PL_sv_yes : &PL_sv_no;
1437 MUTEX_UNLOCK(&thread->mutex);
1438 /* XSRETURN(1); - implied */
1442 ithread_wantarray(...)
1446 PERL_UNUSED_VAR(items);
1447 thread = S_SV_to_ithread(aTHX_ ST(0));
1448 ST(0) = (thread->gimme & G_ARRAY) ? &PL_sv_yes :
1449 (thread->gimme & G_VOID) ? &PL_sv_undef
1450 /* G_SCALAR */ : &PL_sv_no;
1451 /* XSRETURN(1); - implied */
1455 ithread_set_thread_exit_only(...)
1460 Perl_croak(aTHX_ "Usage: ->set_thread_exit_only(boolean)");
1462 thread = S_SV_to_ithread(aTHX_ ST(0));
1463 MUTEX_LOCK(&thread->mutex);
1464 if (SvTRUE(ST(1))) {
1465 thread->state |= PERL_ITHR_THREAD_EXIT_ONLY;
1467 thread->state &= ~PERL_ITHR_THREAD_EXIT_ONLY;
1469 MUTEX_UNLOCK(&thread->mutex);
1478 /* Object method only */
1479 if ((items != 1) || ! sv_isobject(ST(0))) {
1480 Perl_croak(aTHX_ "Usage: $thr->err()");
1483 thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1484 MUTEX_LOCK(&thread->mutex);
1486 /* If thread died, then clone the error into the calling thread */
1487 if (thread->state & PERL_ITHR_DIED) {
1488 PerlInterpreter *other_perl;
1489 CLONE_PARAMS clone_params;
1490 ithread *current_thread;
1492 other_perl = thread->interp;
1493 clone_params.stashes = newAV();
1494 clone_params.flags = CLONEf_JOIN_IN;
1495 PL_ptr_table = ptr_table_new();
1496 current_thread = S_ithread_get(aTHX);
1497 S_ithread_set(aTHX_ thread);
1498 /* Ensure 'meaningful' addresses retain their meaning */
1499 ptr_table_store(PL_ptr_table, &other_perl->Isv_undef, &PL_sv_undef);
1500 ptr_table_store(PL_ptr_table, &other_perl->Isv_no, &PL_sv_no);
1501 ptr_table_store(PL_ptr_table, &other_perl->Isv_yes, &PL_sv_yes);
1502 err = sv_dup(thread->err, &clone_params);
1503 S_ithread_set(aTHX_ current_thread);
1504 SvREFCNT_dec(clone_params.stashes);
1505 SvREFCNT_inc_void(err);
1506 /* If error was an object, bless it into the correct class */
1507 if (thread->err_class) {
1508 sv_bless(err, gv_stashpv(thread->err_class, 1));
1510 ptr_table_free(PL_ptr_table);
1511 PL_ptr_table = NULL;
1514 MUTEX_UNLOCK(&thread->mutex);
1520 ST(0) = sv_2mortal(err);
1521 /* XSRETURN(1); - implied */
1524 #endif /* USE_ITHREADS */
1530 SV *my_pool_sv = *hv_fetch(PL_modglobal, MY_POOL_KEY,
1531 sizeof(MY_POOL_KEY)-1, TRUE);
1532 my_pool_t *my_poolp = (my_pool_t*)SvPVX(newSV(sizeof(my_pool_t)-1));
1536 Zero(my_poolp, 1, my_pool_t);
1537 sv_setuv(my_pool_sv, PTR2UV(my_poolp));
1539 PL_perl_destruct_level = 2;
1540 MUTEX_INIT(&MY_POOL.create_destruct_mutex);
1541 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
1543 PL_threadhook = &Perl_ithread_hook;
1545 MY_POOL.tid_counter = 1;
1546 # ifdef THREAD_CREATE_NEEDS_STACK
1547 MY_POOL.default_stack_size = THREAD_CREATE_NEEDS_STACK;
1550 /* The 'main' thread is thread 0.
1551 * It is detached (unjoinable) and immortal.
1554 MUTEX_INIT(&MY_POOL.main_thread.mutex);
1556 /* Head of the threads list */
1557 MY_POOL.main_thread.next = &MY_POOL.main_thread;
1558 MY_POOL.main_thread.prev = &MY_POOL.main_thread;
1560 MY_POOL.main_thread.count = 1; /* Immortal */
1562 MY_POOL.main_thread.interp = aTHX;
1563 MY_POOL.main_thread.state = PERL_ITHR_DETACHED; /* Detached */
1564 MY_POOL.main_thread.stack_size = MY_POOL.default_stack_size;
1566 MY_POOL.main_thread.thr = GetCurrentThreadId();
1568 MY_POOL.main_thread.thr = pthread_self();
1571 S_ithread_set(aTHX_ &MY_POOL.main_thread);
1572 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
1573 #endif /* USE_ITHREADS */