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
49 #define PERL_ITHR_JOINED 2
50 #define PERL_ITHR_FINISHED 4
51 #define PERL_ITHR_THREAD_EXIT_ONLY 8
52 #define PERL_ITHR_NONVIABLE 16
53 #define PERL_ITHR_DESTROYED 32
54 #define PERL_ITHR_DIED 64
56 typedef struct _ithread {
57 struct _ithread *next; /* Next thread in the list */
58 struct _ithread *prev; /* Prev thread in the list */
59 PerlInterpreter *interp; /* The threads interpreter */
60 UV tid; /* Threads module's thread id */
61 perl_mutex mutex; /* Mutex for updating things in this struct */
62 int count; /* How many SVs have a reference to us */
63 int state; /* Detached, joined, finished, etc. */
64 int gimme; /* Context of create */
65 SV *init_function; /* Code to run */
66 SV *params; /* Args to pass function */
68 DWORD thr; /* OS's idea if thread id */
69 HANDLE handle; /* OS's waitable handle */
71 pthread_t thr; /* OS's handle for the thread */
74 SV *err; /* Error from abnormally terminated thread */
75 char *err_class; /* Error object's classname if applicable */
79 #define MY_CXT_KEY "threads::_cxt" XS_VERSION
82 /* Used by Perl interpreter for thread context switching */
89 #define MY_POOL_KEY "threads::_pool" XS_VERSION
92 /* Structure for 'main' thread
93 * Also forms the 'base' for the doubly-linked list of threads */
96 /* Protects the creation and destruction of threads*/
97 perl_mutex create_destruct_mutex;
103 IV default_stack_size;
108 SV *my_pool_sv = *hv_fetch(PL_modglobal, MY_POOL_KEY, \
109 sizeof(MY_POOL_KEY)-1, TRUE); \
110 my_pool_t *my_poolp = INT2PTR(my_pool_t*, SvUV(my_pool_sv))
112 #define MY_POOL (*my_poolp)
115 /* Used by Perl interpreter for thread context switching */
117 S_ithread_set(pTHX_ ithread *thread)
120 MY_CXT.context = thread;
127 return (MY_CXT.context);
131 /* Free any data (such as the Perl interpreter) attached to an ithread
132 * structure. This is a bit like undef on SVs, where the SV isn't freed,
133 * but the PVX is. Must be called with thread->mutex already held.
136 S_ithread_clear(pTHX_ ithread *thread)
138 PerlInterpreter *interp;
140 assert(((thread->state & PERL_ITHR_FINISHED) &&
141 (thread->state & (PERL_ITHR_DETACHED|PERL_ITHR_JOINED)))
143 (thread->state & PERL_ITHR_NONVIABLE));
145 interp = thread->interp;
149 PERL_SET_CONTEXT(interp);
150 S_ithread_set(aTHX_ thread);
152 SvREFCNT_dec(thread->params);
153 thread->params = Nullsv;
156 SvREFCNT_dec(thread->err);
157 thread->err = Nullsv;
160 perl_destruct(interp);
162 thread->interp = NULL;
165 PERL_SET_CONTEXT(aTHX);
169 /* Free an ithread structure and any attached data if its count == 0 */
171 S_ithread_destruct(pTHX_ ithread *thread)
179 /* Determine if thread can be destroyed now */
180 MUTEX_LOCK(&thread->mutex);
181 if (thread->count != 0) {
183 } else if (thread->state & PERL_ITHR_DESTROYED) {
185 } else if (thread->state & PERL_ITHR_NONVIABLE) {
186 thread->state |= PERL_ITHR_DESTROYED;
188 } else if (! (thread->state & PERL_ITHR_FINISHED)) {
190 } else if (! (thread->state & (PERL_ITHR_DETACHED|PERL_ITHR_JOINED))) {
193 thread->state |= PERL_ITHR_DESTROYED;
196 MUTEX_UNLOCK(&thread->mutex);
197 if (! destroy) return;
199 /* Main thread (0) is immortal and should never get here */
200 assert(thread->tid != 0);
202 /* Remove from circular list of threads */
203 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
204 assert(thread->prev && thread->next);
205 thread->next->prev = thread->prev;
206 thread->prev->next = thread->next;
209 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
211 /* Thread is now disowned */
212 MUTEX_LOCK(&thread->mutex);
213 S_ithread_clear(aTHX_ thread);
216 handle = thread->handle;
217 thread->handle = NULL;
219 MUTEX_UNLOCK(&thread->mutex);
220 MUTEX_DESTROY(&thread->mutex);
228 /* Call PerlMemShared_free() in the context of the "first" interpreter
229 * per http://www.nntp.perl.org/group/perl.perl5.porters/110772
231 aTHX = MY_POOL.main_thread.interp;
232 PerlMemShared_free(thread);
236 /* Warn if exiting with any unjoined threads */
243 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
244 veto_cleanup = (MY_POOL.running_threads || MY_POOL.joinable_threads);
245 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
248 if (ckWARN_d(WARN_THREADS)) {
249 Perl_warn(aTHX_ "Perl exited with active threads:\n\t%"
250 IVdf " running and unjoined\n\t%"
251 IVdf " finished and unjoined\n\t%"
252 IVdf " running and detached\n",
253 MY_POOL.running_threads,
254 MY_POOL.joinable_threads,
255 MY_POOL.detached_threads);
259 return (veto_cleanup);
262 /* Called on exit from main thread */
264 Perl_ithread_hook(pTHX)
267 return ((aTHX == MY_POOL.main_thread.interp) ? S_exit_warning(aTHX) : 0);
271 /* MAGIC (in mg.h sense) hooks */
274 ithread_mg_get(pTHX_ SV *sv, MAGIC *mg)
276 ithread *thread = (ithread *)mg->mg_ptr;
277 SvIV_set(sv, PTR2IV(thread));
283 ithread_mg_free(pTHX_ SV *sv, MAGIC *mg)
285 ithread *thread = (ithread *)mg->mg_ptr;
287 MUTEX_LOCK(&thread->mutex);
289 MUTEX_UNLOCK(&thread->mutex);
291 /* Try to clean up thread */
292 S_ithread_destruct(aTHX_ thread);
298 ithread_mg_dup(pTHX_ MAGIC *mg, CLONE_PARAMS *param)
300 ithread *thread = (ithread *)mg->mg_ptr;
301 MUTEX_LOCK(&thread->mutex);
303 MUTEX_UNLOCK(&thread->mutex);
307 MGVTBL ithread_vtbl = {
308 ithread_mg_get, /* get */
312 ithread_mg_free, /* free */
314 ithread_mg_dup /* dup */
318 /* Provided default, minimum and rational stack sizes */
320 S_good_stack_size(pTHX_ IV stack_size)
324 /* Use default stack size if no stack size specified */
326 return (MY_POOL.default_stack_size);
329 #ifdef PTHREAD_STACK_MIN
330 /* Can't use less than minimum */
331 if (stack_size < PTHREAD_STACK_MIN) {
332 if (ckWARN(WARN_THREADS)) {
333 Perl_warn(aTHX_ "Using minimum thread stack size of %" IVdf, (IV)PTHREAD_STACK_MIN);
335 return (PTHREAD_STACK_MIN);
339 /* Round up to page size boundary */
340 if (MY_POOL.page_size <= 0) {
341 #if defined(HAS_SYSCONF) && (defined(_SC_PAGESIZE) || defined(_SC_MMAP_PAGE_SIZE))
342 SETERRNO(0, SS_NORMAL);
344 MY_POOL.page_size = sysconf(_SC_PAGESIZE);
346 MY_POOL.page_size = sysconf(_SC_MMAP_PAGE_SIZE);
348 if ((long)MY_POOL.page_size < 0) {
350 SV * const error = get_sv("@", FALSE);
351 (void)SvUPGRADE(error, SVt_PV);
352 Perl_croak(aTHX_ "PANIC: sysconf: %s", SvPV_nolen(error));
354 Perl_croak(aTHX_ "PANIC: sysconf: pagesize unknown");
358 # ifdef HAS_GETPAGESIZE
359 MY_POOL.page_size = getpagesize();
361 # if defined(I_SYS_PARAM) && defined(PAGESIZE)
362 MY_POOL.page_size = PAGESIZE;
364 MY_POOL.page_size = 8192; /* A conservative default */
367 if (MY_POOL.page_size <= 0) {
368 Perl_croak(aTHX_ "PANIC: bad pagesize %" IVdf, (IV)MY_POOL.page_size);
372 stack_size = ((stack_size + (MY_POOL.page_size - 1)) / MY_POOL.page_size) * MY_POOL.page_size;
378 /* Starts executing the thread.
379 * Passed as the C level function to run in the new thread.
382 STATIC THREAD_RET_TYPE
383 S_ithread_run(LPVOID arg)
386 S_ithread_run(void * arg)
389 ithread *thread = (ithread *)arg;
392 int exit_app = 0; /* Thread terminated using 'exit' */
394 int died = 0; /* Thread terminated abnormally */
398 dTHXa(thread->interp);
402 /* Blocked until ->create() call finishes */
403 MUTEX_LOCK(&thread->mutex);
404 MUTEX_UNLOCK(&thread->mutex);
406 PERL_SET_CONTEXT(thread->interp);
407 S_ithread_set(aTHX_ thread);
409 PL_perl_destruct_level = 2;
412 AV *params = (AV *)SvRV(thread->params);
413 int len = (int)av_len(params)+1;
420 /* Put args on the stack */
422 for (ii=0; ii < len; ii++) {
423 XPUSHs(av_shift(params));
427 oldscope = PL_scopestack_ix;
430 /* Run the specified function */
431 len = (int)call_sv(thread->init_function, thread->gimme|G_EVAL);
432 } else if (jmp_rc == 2) {
435 exit_code = STATUS_CURRENT;
436 while (PL_scopestack_ix > oldscope) {
442 /* Remove args from stack and put back in params array */
444 for (ii=len-1; ii >= 0; ii--) {
447 av_store(params, ii, SvREFCNT_inc(sv));
454 /* Check for abnormal termination */
456 died = PERL_ITHR_DIED;
457 thread->err = newSVsv(ERRSV);
458 /* If ERRSV is an object, remember the classname and then
459 * rebless into 'main' so it will survive 'cloning'
461 if (sv_isobject(thread->err)) {
462 thread->err_class = HvNAME(SvSTASH(SvRV(thread->err)));
463 sv_bless(thread->err, gv_stashpv("main", 0));
466 if (ckWARN_d(WARN_THREADS)) {
467 oldscope = PL_scopestack_ix;
470 /* Warn that thread died */
471 Perl_warn(aTHX_ "Thread %" UVuf " terminated abnormally: %" SVf, thread->tid, ERRSV);
472 } else if (jmp_rc == 2) {
473 /* Warn handler exited */
475 exit_code = STATUS_CURRENT;
476 while (PL_scopestack_ix > oldscope) {
484 /* Release function ref */
485 SvREFCNT_dec(thread->init_function);
486 thread->init_function = Nullsv;
489 PerlIO_flush((PerlIO *)NULL);
491 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
492 MUTEX_LOCK(&thread->mutex);
493 /* Mark as finished */
494 thread->state |= (PERL_ITHR_FINISHED | died);
495 /* Clear exit flag if required */
496 if (thread->state & PERL_ITHR_THREAD_EXIT_ONLY) {
500 /* Adjust thread status counts */
501 if (thread->state & PERL_ITHR_DETACHED) {
502 MY_POOL.detached_threads--;
504 MY_POOL.running_threads--;
505 MY_POOL.joinable_threads++;
507 MUTEX_UNLOCK(&thread->mutex);
508 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
510 /* Exit application if required */
512 oldscope = PL_scopestack_ix;
515 /* Warn if there are unjoined threads */
516 S_exit_warning(aTHX);
517 } else if (jmp_rc == 2) {
518 /* Warn handler exited */
519 exit_code = STATUS_CURRENT;
520 while (PL_scopestack_ix > oldscope) {
529 /* Try to clean up thread */
530 S_ithread_destruct(aTHX_ thread);
540 /* Type conversion helper functions */
543 S_ithread_to_SV(pTHX_ SV *obj, ithread *thread, char *classname, bool inc)
548 /* If incrementing thread ref count, then call within mutex lock */
550 MUTEX_LOCK(&thread->mutex);
552 MUTEX_UNLOCK(&thread->mutex);
559 sv = newSVrv(obj, classname);
560 sv_setiv(sv, PTR2IV(thread));
561 mg = sv_magicext(sv, Nullsv, PERL_MAGIC_shared_scalar, &ithread_vtbl, (char *)thread, 0);
562 mg->mg_flags |= MGf_DUP;
569 S_SV_to_ithread(pTHX_ SV *sv)
571 /* Argument is a thread */
573 return (INT2PTR(ithread *, SvIV(SvRV(sv))));
575 /* Argument is classname, therefore return current thread */
576 return (S_ithread_get(aTHX));
581 * Called in context of parent thread.
582 * Called with MY_POOL.create_destruct_mutex locked. (Unlocked on error.)
586 pTHX_ SV *init_function,
593 ithread *current_thread = S_ithread_get(aTHX);
595 SV **tmps_tmp = PL_tmps_stack;
596 IV tmps_ix = PL_tmps_ix;
598 int rc_stack_size = 0;
599 int rc_thread_create = 0;
603 /* Allocate thread structure in context of the main thread's interpreter */
605 PERL_SET_CONTEXT(MY_POOL.main_thread.interp);
606 thread = (ithread *)PerlMemShared_malloc(sizeof(ithread));
608 PERL_SET_CONTEXT(aTHX);
610 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
611 PerlLIO_write(PerlIO_fileno(Perl_error_log), PL_no_mem, strlen(PL_no_mem));
614 Zero(thread, 1, ithread);
616 /* Add to threads list */
617 thread->next = &MY_POOL.main_thread;
618 thread->prev = MY_POOL.main_thread.prev;
619 MY_POOL.main_thread.prev = thread;
620 thread->prev->next = thread;
622 /* Set count to 1 immediately in case thread exits before
623 * we return to caller!
627 /* Block new thread until ->create() call finishes */
628 MUTEX_INIT(&thread->mutex);
629 MUTEX_LOCK(&thread->mutex);
631 thread->tid = MY_POOL.tid_counter++;
632 thread->stack_size = S_good_stack_size(aTHX_ stack_size);
633 thread->gimme = gimme;
634 thread->state = exit_opt;
636 /* "Clone" our interpreter into the thread's interpreter.
637 * This gives thread access to "static data" and code.
639 PerlIO_flush((PerlIO *)NULL);
640 S_ithread_set(aTHX_ thread);
642 SAVEBOOL(PL_srand_called); /* Save this so it becomes the correct value */
643 PL_srand_called = FALSE; /* Set it to false so we can detect if it gets
644 set during the clone */
647 thread->interp = perl_clone(aTHX, CLONEf_KEEP_PTR_TABLE | CLONEf_CLONE_HOST);
649 thread->interp = perl_clone(aTHX, CLONEf_KEEP_PTR_TABLE);
652 /* perl_clone() leaves us in new interpreter's context. As it is tricky
653 * to spot an implicit aTHX, create a new scope with aTHX matching the
654 * context for the duration of our work for new interpreter.
657 CLONE_PARAMS clone_param;
659 dTHXa(thread->interp);
663 /* Here we remove END blocks since they should only run in the thread
666 SvREFCNT_dec(PL_endav);
669 clone_param.flags = 0;
670 if (SvPOK(init_function)) {
671 thread->init_function = newSV(0);
672 sv_copypv(thread->init_function, init_function);
674 thread->init_function = sv_dup(init_function, &clone_param);
675 if (SvREFCNT(thread->init_function) == 0) {
676 SvREFCNT_inc_void(thread->init_function);
680 thread->params = sv_dup(params, &clone_param);
681 SvREFCNT_inc_void(thread->params);
683 /* The code below checks that anything living on the tmps stack and
684 * has been cloned (so it lives in the ptr_table) has a refcount
687 * If the refcount is 0 it means that a something on the stack/context
688 * was holding a reference to it and since we init_stacks() in
689 * perl_clone that won't get cleaned and we will get a leaked scalar.
690 * The reason it was cloned was that it lived on the @_ stack.
692 * Example of this can be found in bugreport 15837 where calls in the
693 * parameter list end up as a temp.
695 * One could argue that this fix should be in perl_clone.
697 while (tmps_ix > 0) {
698 SV* sv = (SV*)ptr_table_fetch(PL_ptr_table, tmps_tmp[tmps_ix]);
700 if (sv && SvREFCNT(sv) == 0) {
701 SvREFCNT_inc_void(sv);
706 SvTEMP_off(thread->init_function);
707 ptr_table_free(PL_ptr_table);
709 PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
711 S_ithread_set(aTHX_ current_thread);
712 PERL_SET_CONTEXT(aTHX);
714 /* Create/start the thread */
716 thread->handle = CreateThread(NULL,
717 (DWORD)thread->stack_size,
720 STACK_SIZE_PARAM_IS_A_RESERVATION,
724 STATIC pthread_attr_t attr;
725 STATIC int attr_inited = 0;
726 STATIC int attr_joinable = PTHREAD_CREATE_JOINABLE;
728 pthread_attr_init(&attr);
732 # ifdef PTHREAD_ATTR_SETDETACHSTATE
733 /* Threads start out joinable */
734 PTHREAD_ATTR_SETDETACHSTATE(&attr, attr_joinable);
737 # ifdef _POSIX_THREAD_ATTR_STACKSIZE
738 /* Set thread's stack size */
739 if (thread->stack_size > 0) {
740 rc_stack_size = pthread_attr_setstacksize(&attr, (size_t)thread->stack_size);
744 /* Create the thread */
745 if (! rc_stack_size) {
746 # ifdef OLD_PTHREADS_API
747 rc_thread_create = pthread_create(&thread->thr,
752 # if defined(HAS_PTHREAD_ATTR_SETSCOPE) && defined(PTHREAD_SCOPE_SYSTEM)
753 pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);
755 rc_thread_create = pthread_create(&thread->thr,
762 # ifdef _POSIX_THREAD_ATTR_STACKSIZE
763 /* Try to get thread's actual stack size */
767 stacksize = pthread_attr_getstacksize(attr);
769 if (! pthread_attr_getstacksize(&attr, &stacksize))
772 thread->stack_size = (IV)stacksize;
779 /* Check for errors */
781 if (thread->handle == NULL) {
783 if (rc_stack_size || rc_thread_create) {
785 /* Must unlock mutex for destruct call */
786 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
788 thread->state |= PERL_ITHR_NONVIABLE;
789 S_ithread_destruct(aTHX_ thread);
791 if (ckWARN_d(WARN_THREADS)) {
793 Perl_warn(aTHX_ "Thread creation failed: pthread_attr_setstacksize(%" IVdf ") returned %d", thread->stack_size, rc_stack_size);
795 Perl_warn(aTHX_ "Thread creation failed: pthread_create returned %d", rc_thread_create);
802 MY_POOL.running_threads++;
807 #endif /* USE_ITHREADS */
810 MODULE = threads PACKAGE = threads PREFIX = ithread_
820 SV *function_to_call;
826 SV *thread_exit_only;
832 if ((items >= 2) && SvROK(ST(1)) && SvTYPE(SvRV(ST(1)))==SVt_PVHV) {
834 Perl_croak(aTHX_ "Usage: threads->create(\\%specs, function, ...)");
836 specs = (HV*)SvRV(ST(1));
840 Perl_croak(aTHX_ "Usage: threads->create(function, ...)");
846 if (sv_isobject(ST(0))) {
848 classname = HvNAME(SvSTASH(SvRV(ST(0))));
849 thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
850 stack_size = thread->stack_size;
851 exit_opt = thread->state & PERL_ITHR_THREAD_EXIT_ONLY;
853 /* threads->create() */
854 classname = (char *)SvPV_nolen(ST(0));
855 stack_size = MY_POOL.default_stack_size;
856 thread_exit_only = get_sv("threads::thread_exit_only", TRUE);
857 exit_opt = (SvTRUE(thread_exit_only))
858 ? PERL_ITHR_THREAD_EXIT_ONLY : 0;
861 function_to_call = ST(idx+1);
866 if (hv_exists(specs, "stack", 5)) {
867 stack_size = SvIV(*hv_fetch(specs, "stack", 5, 0));
868 } else if (hv_exists(specs, "stacksize", 9)) {
869 stack_size = SvIV(*hv_fetch(specs, "stacksize", 9, 0));
870 } else if (hv_exists(specs, "stack_size", 10)) {
871 stack_size = SvIV(*hv_fetch(specs, "stack_size", 10, 0));
875 if (hv_exists(specs, "context", 7)) {
876 str = (char *)SvPV_nolen(*hv_fetch(specs, "context", 7, 0));
891 Perl_croak(aTHX_ "Invalid context: %s", str);
893 } else if (hv_exists(specs, "array", 5)) {
894 if (SvTRUE(*hv_fetch(specs, "array", 5, 0))) {
897 } else if (hv_exists(specs, "scalar", 6)) {
898 if (SvTRUE(*hv_fetch(specs, "scalar", 6, 0))) {
901 } else if (hv_exists(specs, "void", 4)) {
902 if (SvTRUE(*hv_fetch(specs, "void", 4, 0))) {
907 /* exit => thread_only */
908 if (hv_exists(specs, "exit", 4)) {
909 str = (char *)SvPV_nolen(*hv_fetch(specs, "exit", 4, 0));
910 exit_opt = (*str == 't' || *str == 'T')
911 ? PERL_ITHR_THREAD_EXIT_ONLY : 0;
915 context = GIMME_V; /* Implicit context */
917 context |= (GIMME_V & (~(G_ARRAY|G_SCALAR|G_VOID)));
923 for (ii=2; ii < items ; ii++) {
924 av_push(params, SvREFCNT_inc(ST(idx+ii)));
929 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
930 thread = S_ithread_create(aTHX_ function_to_call,
934 newRV_noinc((SV*)params));
936 XSRETURN_UNDEF; /* Mutex already unlocked */
938 ST(0) = sv_2mortal(S_ithread_to_SV(aTHX_ Nullsv, thread, classname, FALSE));
939 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
942 MUTEX_UNLOCK(&thread->mutex);
944 /* XSRETURN(1); - implied */
954 int want_running = 0;
957 /* Class method only */
959 Perl_croak(aTHX_ "Usage: threads->list(...)");
961 classname = (char *)SvPV_nolen(ST(0));
963 /* Calling context */
964 list_context = (GIMME_V == G_ARRAY);
966 /* Running or joinable parameter */
968 want_running = SvTRUE(ST(1));
971 /* Walk through threads list */
972 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
973 for (thread = MY_POOL.main_thread.next;
974 thread != &MY_POOL.main_thread;
975 thread = thread->next)
977 /* Ignore detached or joined threads */
978 if (thread->state & (PERL_ITHR_DETACHED|PERL_ITHR_JOINED)) {
982 /* Filter per parameter */
985 if (thread->state & PERL_ITHR_FINISHED) {
986 continue; /* Not running */
989 if (! (thread->state & PERL_ITHR_FINISHED)) {
990 continue; /* Still running - not joinable yet */
995 /* Push object on stack if list context */
997 XPUSHs(sv_2mortal(S_ithread_to_SV(aTHX_ Nullsv, thread, classname, TRUE)));
1001 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
1002 /* If scalar context, send back count */
1003 if (! list_context) {
1014 /* Class method only */
1015 if ((items != 1) || SvROK(ST(0))) {
1016 Perl_croak(aTHX_ "Usage: threads->self()");
1018 classname = (char *)SvPV_nolen(ST(0));
1020 thread = S_ithread_get(aTHX);
1022 ST(0) = sv_2mortal(S_ithread_to_SV(aTHX_ Nullsv, thread, classname, TRUE));
1023 /* XSRETURN(1); - implied */
1031 PERL_UNUSED_VAR(items);
1032 thread = S_SV_to_ithread(aTHX_ ST(0));
1033 XST_mUV(0, thread->tid);
1034 /* XSRETURN(1); - implied */
1052 /* Object method only */
1053 if ((items != 1) || ! sv_isobject(ST(0))) {
1054 Perl_croak(aTHX_ "Usage: $thr->join()");
1057 /* Check if the thread is joinable */
1058 thread = S_SV_to_ithread(aTHX_ ST(0));
1059 join_err = (thread->state & (PERL_ITHR_DETACHED|PERL_ITHR_JOINED));
1061 if (join_err & PERL_ITHR_DETACHED) {
1062 Perl_croak(aTHX_ "Cannot join a detached thread");
1064 Perl_croak(aTHX_ "Thread already joined");
1068 /* Join the thread */
1070 waitcode = WaitForSingleObject(thread->handle, INFINITE);
1072 pthread_join(thread->thr, &retval);
1075 MUTEX_LOCK(&thread->mutex);
1076 /* Mark as joined */
1077 thread->state |= PERL_ITHR_JOINED;
1079 /* Get the return value from the call_sv */
1080 /* Objects do not survive this process - FIXME */
1083 PerlInterpreter *other_perl;
1084 CLONE_PARAMS clone_params;
1085 ithread *current_thread;
1087 params_copy = (AV *)SvRV(thread->params);
1088 other_perl = thread->interp;
1089 clone_params.stashes = newAV();
1090 clone_params.flags = CLONEf_JOIN_IN;
1091 PL_ptr_table = ptr_table_new();
1092 current_thread = S_ithread_get(aTHX);
1093 S_ithread_set(aTHX_ thread);
1094 /* Ensure 'meaningful' addresses retain their meaning */
1095 ptr_table_store(PL_ptr_table, &other_perl->Isv_undef, &PL_sv_undef);
1096 ptr_table_store(PL_ptr_table, &other_perl->Isv_no, &PL_sv_no);
1097 ptr_table_store(PL_ptr_table, &other_perl->Isv_yes, &PL_sv_yes);
1098 params = (AV *)sv_dup((SV*)params_copy, &clone_params);
1099 S_ithread_set(aTHX_ current_thread);
1100 SvREFCNT_dec(clone_params.stashes);
1101 SvREFCNT_inc_void(params);
1102 ptr_table_free(PL_ptr_table);
1103 PL_ptr_table = NULL;
1106 /* If thread didn't die, then we can free its interpreter */
1107 if (! (thread->state & PERL_ITHR_DIED)) {
1108 S_ithread_clear(aTHX_ thread);
1110 MUTEX_UNLOCK(&thread->mutex);
1112 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
1113 if (! (thread->state & PERL_ITHR_DETACHED)) {
1114 MY_POOL.joinable_threads--;
1116 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
1118 /* Try to cleanup thread */
1119 S_ithread_destruct(aTHX_ thread);
1121 /* If no return values, then just return */
1126 /* Put return values on stack */
1127 len = (int)AvFILL(params);
1128 for (ii=0; ii <= len; ii++) {
1129 SV* param = av_shift(params);
1130 XPUSHs(sv_2mortal(param));
1133 /* Free return value array */
1134 SvREFCNT_dec(params);
1140 PERL_UNUSED_VAR(items);
1151 PERL_UNUSED_VAR(items);
1153 /* Check if the thread is detachable */
1154 thread = S_SV_to_ithread(aTHX_ ST(0));
1155 if ((detach_err = (thread->state & (PERL_ITHR_DETACHED|PERL_ITHR_JOINED)))) {
1156 if (detach_err & PERL_ITHR_DETACHED) {
1157 Perl_croak(aTHX_ "Thread already detached");
1159 Perl_croak(aTHX_ "Cannot detach a joined thread");
1163 /* Detach the thread */
1164 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
1165 MUTEX_LOCK(&thread->mutex);
1166 thread->state |= PERL_ITHR_DETACHED;
1168 /* Windows has no 'detach thread' function */
1170 PERL_THREAD_DETACH(thread->thr);
1172 if (thread->state & PERL_ITHR_FINISHED) {
1173 MY_POOL.joinable_threads--;
1175 MY_POOL.running_threads--;
1176 MY_POOL.detached_threads++;
1178 MUTEX_UNLOCK(&thread->mutex);
1179 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
1181 /* If thread is finished and didn't die,
1182 * then we can free its interpreter */
1183 MUTEX_LOCK(&thread->mutex);
1184 if ((thread->state & PERL_ITHR_FINISHED) &&
1185 ! (thread->state & PERL_ITHR_DIED))
1187 S_ithread_clear(aTHX_ thread);
1189 MUTEX_UNLOCK(&thread->mutex);
1191 /* Try to cleanup thread */
1192 S_ithread_destruct(aTHX_ thread);
1202 /* Must have safe signals */
1203 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG) {
1204 Perl_croak(aTHX_ "Cannot signal threads without safe signals");
1207 /* Object method only */
1208 if ((items != 2) || ! sv_isobject(ST(0))) {
1209 Perl_croak(aTHX_ "Usage: $thr->kill('SIG...')");
1213 sig_name = SvPV_nolen(ST(1));
1214 if (isALPHA(*sig_name)) {
1215 if (*sig_name == 'S' && sig_name[1] == 'I' && sig_name[2] == 'G') {
1218 if ((signal = whichsig(sig_name)) < 0) {
1219 Perl_croak(aTHX_ "Unrecognized signal name: %s", sig_name);
1222 signal = SvIV(ST(1));
1225 /* Set the signal for the thread */
1226 thread = S_SV_to_ithread(aTHX_ ST(0));
1227 MUTEX_LOCK(&thread->mutex);
1228 if (thread->interp) {
1229 dTHXa(thread->interp);
1230 PL_psig_pend[signal]++;
1233 MUTEX_UNLOCK(&thread->mutex);
1235 /* Return the thread to allow for method chaining */
1237 /* XSRETURN(1); - implied */
1241 ithread_DESTROY(...)
1243 PERL_UNUSED_VAR(items);
1244 sv_unmagic(SvRV(ST(0)), PERL_MAGIC_shared_scalar);
1252 PERL_UNUSED_VAR(items);
1254 /* Compares TIDs to determine thread equality */
1255 if (sv_isobject(ST(0)) && sv_isobject(ST(1))) {
1256 ithread *thr1 = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1257 ithread *thr2 = INT2PTR(ithread *, SvIV(SvRV(ST(1))));
1258 are_equal = (thr1->tid == thr2->tid);
1263 /* Return 0 on false for backward compatibility */
1266 /* XSRETURN(1); - implied */
1278 /* Class method only */
1280 Perl_croak(aTHX_ "Usage: threads->object($tid)");
1282 classname = (char *)SvPV_nolen(ST(0));
1284 if ((items < 2) || ! SvOK(ST(1))) {
1288 /* threads->object($tid) */
1291 /* Walk through threads list */
1292 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
1293 for (thread = MY_POOL.main_thread.next;
1294 thread != &MY_POOL.main_thread;
1295 thread = thread->next)
1298 if (thread->tid == tid) {
1299 /* Ignore if detached or joined */
1300 if (! (thread->state & (PERL_ITHR_DETACHED|PERL_ITHR_JOINED))) {
1301 /* Put object on stack */
1302 ST(0) = sv_2mortal(S_ithread_to_SV(aTHX_ Nullsv, thread, classname, TRUE));
1308 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
1313 /* XSRETURN(1); - implied */
1317 ithread__handle(...);
1321 PERL_UNUSED_VAR(items);
1322 thread = S_SV_to_ithread(aTHX_ ST(0));
1324 XST_mUV(0, PTR2UV(&thread->handle));
1326 XST_mUV(0, PTR2UV(&thread->thr));
1328 /* XSRETURN(1); - implied */
1332 ithread_get_stack_size(...)
1337 PERL_UNUSED_VAR(items);
1338 if (sv_isobject(ST(0))) {
1339 /* $thr->get_stack_size() */
1340 ithread *thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1341 stack_size = thread->stack_size;
1343 /* threads->get_stack_size() */
1344 stack_size = MY_POOL.default_stack_size;
1346 XST_mIV(0, stack_size);
1347 /* XSRETURN(1); - implied */
1351 ithread_set_stack_size(...)
1357 Perl_croak(aTHX_ "Usage: threads->set_stack_size($size)");
1359 if (sv_isobject(ST(0))) {
1360 Perl_croak(aTHX_ "Cannot change stack size of an existing thread");
1363 old_size = MY_POOL.default_stack_size;
1364 MY_POOL.default_stack_size = S_good_stack_size(aTHX_ SvIV(ST(1)));
1365 XST_mIV(0, old_size);
1366 /* XSRETURN(1); - implied */
1370 ithread_is_running(...)
1374 /* Object method only */
1375 if ((items != 1) || ! sv_isobject(ST(0))) {
1376 Perl_croak(aTHX_ "Usage: $thr->is_running()");
1379 thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1380 ST(0) = (thread->state & PERL_ITHR_FINISHED) ? &PL_sv_no : &PL_sv_yes;
1381 /* XSRETURN(1); - implied */
1385 ithread_is_detached(...)
1389 PERL_UNUSED_VAR(items);
1390 thread = S_SV_to_ithread(aTHX_ ST(0));
1391 ST(0) = (thread->state & PERL_ITHR_DETACHED) ? &PL_sv_yes : &PL_sv_no;
1392 /* XSRETURN(1); - implied */
1396 ithread_is_joinable(...)
1400 /* Object method only */
1401 if ((items != 1) || ! sv_isobject(ST(0))) {
1402 Perl_croak(aTHX_ "Usage: $thr->is_joinable()");
1405 thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1406 MUTEX_LOCK(&thread->mutex);
1407 ST(0) = ((thread->state & PERL_ITHR_FINISHED) &&
1408 ! (thread->state & (PERL_ITHR_DETACHED|PERL_ITHR_JOINED)))
1409 ? &PL_sv_yes : &PL_sv_no;
1410 MUTEX_UNLOCK(&thread->mutex);
1411 /* XSRETURN(1); - implied */
1415 ithread_wantarray(...)
1419 PERL_UNUSED_VAR(items);
1420 thread = S_SV_to_ithread(aTHX_ ST(0));
1421 ST(0) = (thread->gimme & G_ARRAY) ? &PL_sv_yes :
1422 (thread->gimme & G_VOID) ? &PL_sv_undef
1423 /* G_SCALAR */ : &PL_sv_no;
1424 /* XSRETURN(1); - implied */
1428 ithread_set_thread_exit_only(...)
1433 Perl_croak(aTHX_ "Usage: ->set_thread_exit_only(boolean)");
1435 thread = S_SV_to_ithread(aTHX_ ST(0));
1436 MUTEX_LOCK(&thread->mutex);
1437 if (SvTRUE(ST(1))) {
1438 thread->state |= PERL_ITHR_THREAD_EXIT_ONLY;
1440 thread->state &= ~PERL_ITHR_THREAD_EXIT_ONLY;
1442 MUTEX_UNLOCK(&thread->mutex);
1451 /* Object method only */
1452 if ((items != 1) || ! sv_isobject(ST(0))) {
1453 Perl_croak(aTHX_ "Usage: $thr->err()");
1456 thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1457 MUTEX_LOCK(&thread->mutex);
1459 /* If thread died, then clone the error into the calling thread */
1460 if (thread->state & PERL_ITHR_DIED) {
1461 PerlInterpreter *other_perl;
1462 CLONE_PARAMS clone_params;
1463 ithread *current_thread;
1465 other_perl = thread->interp;
1466 clone_params.stashes = newAV();
1467 clone_params.flags = CLONEf_JOIN_IN;
1468 PL_ptr_table = ptr_table_new();
1469 current_thread = S_ithread_get(aTHX);
1470 S_ithread_set(aTHX_ thread);
1471 /* Ensure 'meaningful' addresses retain their meaning */
1472 ptr_table_store(PL_ptr_table, &other_perl->Isv_undef, &PL_sv_undef);
1473 ptr_table_store(PL_ptr_table, &other_perl->Isv_no, &PL_sv_no);
1474 ptr_table_store(PL_ptr_table, &other_perl->Isv_yes, &PL_sv_yes);
1475 err = sv_dup(thread->err, &clone_params);
1476 S_ithread_set(aTHX_ current_thread);
1477 SvREFCNT_dec(clone_params.stashes);
1478 SvREFCNT_inc_void(err);
1479 /* If error was an object, bless it into the correct class */
1480 if (thread->err_class) {
1481 sv_bless(err, gv_stashpv(thread->err_class, 1));
1483 ptr_table_free(PL_ptr_table);
1484 PL_ptr_table = NULL;
1487 MUTEX_UNLOCK(&thread->mutex);
1493 ST(0) = sv_2mortal(err);
1494 /* XSRETURN(1); - implied */
1497 #endif /* USE_ITHREADS */
1503 SV *my_pool_sv = *hv_fetch(PL_modglobal, MY_POOL_KEY,
1504 sizeof(MY_POOL_KEY)-1, TRUE);
1505 my_pool_t *my_poolp = (my_pool_t*)SvPVX(newSV(sizeof(my_pool_t)-1));
1509 Zero(my_poolp, 1, my_pool_t);
1510 sv_setuv(my_pool_sv, PTR2UV(my_poolp));
1512 PL_perl_destruct_level = 2;
1513 MUTEX_INIT(&MY_POOL.create_destruct_mutex);
1514 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
1516 PL_threadhook = &Perl_ithread_hook;
1518 MY_POOL.tid_counter = 1;
1519 # ifdef THREAD_CREATE_NEEDS_STACK
1520 MY_POOL.default_stack_size = THREAD_CREATE_NEEDS_STACK;
1523 /* The 'main' thread is thread 0.
1524 * It is detached (unjoinable) and immortal.
1527 MUTEX_INIT(&MY_POOL.main_thread.mutex);
1529 /* Head of the threads list */
1530 MY_POOL.main_thread.next = &MY_POOL.main_thread;
1531 MY_POOL.main_thread.prev = &MY_POOL.main_thread;
1533 MY_POOL.main_thread.count = 1; /* Immortal */
1535 MY_POOL.main_thread.interp = aTHX;
1536 MY_POOL.main_thread.state = PERL_ITHR_DETACHED; /* Detached */
1537 MY_POOL.main_thread.stack_size = MY_POOL.default_stack_size;
1539 MY_POOL.main_thread.thr = GetCurrentThreadId();
1541 MY_POOL.main_thread.thr = pthread_self();
1544 S_ithread_set(aTHX_ &MY_POOL.main_thread);
1545 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
1546 #endif /* USE_ITHREADS */