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_UNCALLABLE (PERL_ITHR_DETACHED|PERL_ITHR_JOINED)
51 #define PERL_ITHR_FINISHED 4
52 #define PERL_ITHR_THREAD_EXIT_ONLY 8
53 #define PERL_ITHR_NONVIABLE 16
54 #define PERL_ITHR_DESTROYED 32
55 #define PERL_ITHR_DIED 64
57 typedef struct _ithread {
58 struct _ithread *next; /* Next thread in the list */
59 struct _ithread *prev; /* Prev thread in the list */
60 PerlInterpreter *interp; /* The threads interpreter */
61 UV tid; /* Threads module's thread id */
62 perl_mutex mutex; /* Mutex for updating things in this struct */
63 int count; /* How many SVs have a reference to us */
64 int state; /* Detached, joined, finished, etc. */
65 int gimme; /* Context of create */
66 SV *init_function; /* Code to run */
67 SV *params; /* Args to pass function */
69 DWORD thr; /* OS's idea if thread id */
70 HANDLE handle; /* OS's waitable handle */
72 pthread_t thr; /* OS's handle for the thread */
75 SV *err; /* Error from abnormally terminated thread */
76 char *err_class; /* Error object's classname if applicable */
80 #define MY_CXT_KEY "threads::_cxt" XS_VERSION
83 /* Used by Perl interpreter for thread context switching */
90 #define MY_POOL_KEY "threads::_pool" XS_VERSION
93 /* Structure for 'main' thread
94 * Also forms the 'base' for the doubly-linked list of threads */
97 /* Protects the creation and destruction of threads*/
98 perl_mutex create_destruct_mutex;
104 IV default_stack_size;
109 SV *my_pool_sv = *hv_fetch(PL_modglobal, MY_POOL_KEY, \
110 sizeof(MY_POOL_KEY)-1, TRUE); \
111 my_pool_t *my_poolp = INT2PTR(my_pool_t*, SvUV(my_pool_sv))
113 #define MY_POOL (*my_poolp)
116 /* Used by Perl interpreter for thread context switching */
118 S_ithread_set(pTHX_ ithread *thread)
121 MY_CXT.context = thread;
128 return (MY_CXT.context);
132 /* Free any data (such as the Perl interpreter) attached to an ithread
133 * structure. This is a bit like undef on SVs, where the SV isn't freed,
134 * but the PVX is. Must be called with thread->mutex already held.
137 S_ithread_clear(pTHX_ ithread *thread)
139 PerlInterpreter *interp;
141 assert(((thread->state & PERL_ITHR_FINISHED) &&
142 (thread->state & PERL_ITHR_UNCALLABLE))
144 (thread->state & PERL_ITHR_NONVIABLE));
146 interp = thread->interp;
150 PERL_SET_CONTEXT(interp);
151 S_ithread_set(aTHX_ thread);
153 SvREFCNT_dec(thread->params);
154 thread->params = Nullsv;
157 SvREFCNT_dec(thread->err);
158 thread->err = Nullsv;
161 perl_destruct(interp);
163 thread->interp = NULL;
166 PERL_SET_CONTEXT(aTHX);
170 /* Free an ithread structure and any attached data if its count == 0 */
172 S_ithread_destruct(pTHX_ ithread *thread)
180 /* Determine if thread can be destroyed now */
181 MUTEX_LOCK(&thread->mutex);
182 if (thread->count != 0) {
184 } else if (thread->state & PERL_ITHR_DESTROYED) {
186 } else if (thread->state & PERL_ITHR_NONVIABLE) {
187 thread->state |= PERL_ITHR_DESTROYED;
189 } else if (! (thread->state & PERL_ITHR_FINISHED)) {
191 } else if (! (thread->state & PERL_ITHR_UNCALLABLE)) {
194 thread->state |= PERL_ITHR_DESTROYED;
197 MUTEX_UNLOCK(&thread->mutex);
198 if (! destroy) return;
200 /* Main thread (0) is immortal and should never get here */
201 assert(thread->tid != 0);
203 /* Remove from circular list of threads */
204 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
205 assert(thread->prev && thread->next);
206 thread->next->prev = thread->prev;
207 thread->prev->next = thread->next;
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);
237 /* Warn if exiting with any unjoined threads */
244 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
245 veto_cleanup = (MY_POOL.running_threads || MY_POOL.joinable_threads);
246 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
249 if (ckWARN_d(WARN_THREADS)) {
250 Perl_warn(aTHX_ "Perl exited with active threads:\n\t%"
251 IVdf " running and unjoined\n\t%"
252 IVdf " finished and unjoined\n\t%"
253 IVdf " running and detached\n",
254 MY_POOL.running_threads,
255 MY_POOL.joinable_threads,
256 MY_POOL.detached_threads);
260 return (veto_cleanup);
263 /* Called on exit from main thread */
265 Perl_ithread_hook(pTHX)
268 return ((aTHX == MY_POOL.main_thread.interp) ? S_exit_warning(aTHX) : 0);
272 /* MAGIC (in mg.h sense) hooks */
275 ithread_mg_get(pTHX_ SV *sv, MAGIC *mg)
277 ithread *thread = (ithread *)mg->mg_ptr;
278 SvIV_set(sv, PTR2IV(thread));
284 ithread_mg_free(pTHX_ SV *sv, MAGIC *mg)
286 ithread *thread = (ithread *)mg->mg_ptr;
288 MUTEX_LOCK(&thread->mutex);
290 MUTEX_UNLOCK(&thread->mutex);
292 /* Try to clean up thread */
293 S_ithread_destruct(aTHX_ thread);
299 ithread_mg_dup(pTHX_ MAGIC *mg, CLONE_PARAMS *param)
301 ithread *thread = (ithread *)mg->mg_ptr;
302 MUTEX_LOCK(&thread->mutex);
304 MUTEX_UNLOCK(&thread->mutex);
308 MGVTBL ithread_vtbl = {
309 ithread_mg_get, /* get */
313 ithread_mg_free, /* free */
315 ithread_mg_dup /* dup */
319 /* Provided default, minimum and rational stack sizes */
321 S_good_stack_size(pTHX_ IV stack_size)
325 /* Use default stack size if no stack size specified */
327 return (MY_POOL.default_stack_size);
330 #ifdef PTHREAD_STACK_MIN
331 /* Can't use less than minimum */
332 if (stack_size < PTHREAD_STACK_MIN) {
333 if (ckWARN(WARN_THREADS)) {
334 Perl_warn(aTHX_ "Using minimum thread stack size of %" IVdf, (IV)PTHREAD_STACK_MIN);
336 return (PTHREAD_STACK_MIN);
340 /* Round up to page size boundary */
341 if (MY_POOL.page_size <= 0) {
342 #if defined(HAS_SYSCONF) && (defined(_SC_PAGESIZE) || defined(_SC_MMAP_PAGE_SIZE))
343 SETERRNO(0, SS_NORMAL);
345 MY_POOL.page_size = sysconf(_SC_PAGESIZE);
347 MY_POOL.page_size = sysconf(_SC_MMAP_PAGE_SIZE);
349 if ((long)MY_POOL.page_size < 0) {
351 SV * const error = get_sv("@", FALSE);
352 (void)SvUPGRADE(error, SVt_PV);
353 Perl_croak(aTHX_ "PANIC: sysconf: %s", SvPV_nolen(error));
355 Perl_croak(aTHX_ "PANIC: sysconf: pagesize unknown");
359 # ifdef HAS_GETPAGESIZE
360 MY_POOL.page_size = getpagesize();
362 # if defined(I_SYS_PARAM) && defined(PAGESIZE)
363 MY_POOL.page_size = PAGESIZE;
365 MY_POOL.page_size = 8192; /* A conservative default */
368 if (MY_POOL.page_size <= 0) {
369 Perl_croak(aTHX_ "PANIC: bad pagesize %" IVdf, (IV)MY_POOL.page_size);
373 stack_size = ((stack_size + (MY_POOL.page_size - 1)) / MY_POOL.page_size) * MY_POOL.page_size;
379 /* Starts executing the thread.
380 * Passed as the C level function to run in the new thread.
383 STATIC THREAD_RET_TYPE
384 S_ithread_run(LPVOID arg)
387 S_ithread_run(void * arg)
390 ithread *thread = (ithread *)arg;
393 int exit_app = 0; /* Thread terminated using 'exit' */
395 int died = 0; /* Thread terminated abnormally */
399 dTHXa(thread->interp);
403 /* Blocked until ->create() call finishes */
404 MUTEX_LOCK(&thread->mutex);
405 MUTEX_UNLOCK(&thread->mutex);
407 PERL_SET_CONTEXT(thread->interp);
408 S_ithread_set(aTHX_ thread);
410 PL_perl_destruct_level = 2;
413 AV *params = (AV *)SvRV(thread->params);
414 int len = (int)av_len(params)+1;
421 /* Put args on the stack */
423 for (ii=0; ii < len; ii++) {
424 XPUSHs(av_shift(params));
428 oldscope = PL_scopestack_ix;
431 /* Run the specified function */
432 len = (int)call_sv(thread->init_function, thread->gimme|G_EVAL);
433 } else if (jmp_rc == 2) {
436 exit_code = STATUS_CURRENT;
437 while (PL_scopestack_ix > oldscope) {
443 /* Remove args from stack and put back in params array */
445 for (ii=len-1; ii >= 0; ii--) {
448 av_store(params, ii, SvREFCNT_inc(sv));
455 /* Check for abnormal termination */
457 died = PERL_ITHR_DIED;
458 thread->err = newSVsv(ERRSV);
459 /* If ERRSV is an object, remember the classname and then
460 * rebless into 'main' so it will survive 'cloning'
462 if (sv_isobject(thread->err)) {
463 thread->err_class = HvNAME(SvSTASH(SvRV(thread->err)));
464 sv_bless(thread->err, gv_stashpv("main", 0));
467 if (ckWARN_d(WARN_THREADS)) {
468 oldscope = PL_scopestack_ix;
471 /* Warn that thread died */
472 Perl_warn(aTHX_ "Thread %" UVuf " terminated abnormally: %" SVf, thread->tid, ERRSV);
473 } else if (jmp_rc == 2) {
474 /* Warn handler exited */
476 exit_code = STATUS_CURRENT;
477 while (PL_scopestack_ix > oldscope) {
485 /* Release function ref */
486 SvREFCNT_dec(thread->init_function);
487 thread->init_function = Nullsv;
490 PerlIO_flush((PerlIO *)NULL);
492 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
493 MUTEX_LOCK(&thread->mutex);
494 /* Mark as finished */
495 thread->state |= (PERL_ITHR_FINISHED | died);
496 /* Clear exit flag if required */
497 if (thread->state & PERL_ITHR_THREAD_EXIT_ONLY) {
501 /* Adjust thread status counts */
502 if (thread->state & PERL_ITHR_DETACHED) {
503 MY_POOL.detached_threads--;
505 MY_POOL.running_threads--;
506 MY_POOL.joinable_threads++;
508 MUTEX_UNLOCK(&thread->mutex);
509 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
511 /* Exit application if required */
513 oldscope = PL_scopestack_ix;
516 /* Warn if there are unjoined threads */
517 S_exit_warning(aTHX);
518 } else if (jmp_rc == 2) {
519 /* Warn handler exited */
520 exit_code = STATUS_CURRENT;
521 while (PL_scopestack_ix > oldscope) {
530 /* Try to clean up thread */
531 S_ithread_destruct(aTHX_ thread);
541 /* Type conversion helper functions */
544 S_ithread_to_SV(pTHX_ SV *obj, ithread *thread, char *classname, bool inc)
549 /* If incrementing thread ref count, then call within mutex lock */
551 MUTEX_LOCK(&thread->mutex);
553 MUTEX_UNLOCK(&thread->mutex);
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;
623 /* Set count to 1 immediately in case thread exits before
624 * we return to caller!
628 /* Block new thread until ->create() call finishes */
629 MUTEX_INIT(&thread->mutex);
630 MUTEX_LOCK(&thread->mutex);
632 thread->tid = MY_POOL.tid_counter++;
633 thread->stack_size = S_good_stack_size(aTHX_ stack_size);
634 thread->gimme = gimme;
635 thread->state = exit_opt;
637 /* "Clone" our interpreter into the thread's interpreter.
638 * This gives thread access to "static data" and code.
640 PerlIO_flush((PerlIO *)NULL);
641 S_ithread_set(aTHX_ thread);
643 SAVEBOOL(PL_srand_called); /* Save this so it becomes the correct value */
644 PL_srand_called = FALSE; /* Set it to false so we can detect if it gets
645 set during the clone */
648 thread->interp = perl_clone(aTHX, CLONEf_KEEP_PTR_TABLE | CLONEf_CLONE_HOST);
650 thread->interp = perl_clone(aTHX, CLONEf_KEEP_PTR_TABLE);
653 /* perl_clone() leaves us in new interpreter's context. As it is tricky
654 * to spot an implicit aTHX, create a new scope with aTHX matching the
655 * context for the duration of our work for new interpreter.
658 CLONE_PARAMS clone_param;
660 dTHXa(thread->interp);
664 /* Here we remove END blocks since they should only run in the thread
667 SvREFCNT_dec(PL_endav);
670 clone_param.flags = 0;
671 if (SvPOK(init_function)) {
672 thread->init_function = newSV(0);
673 sv_copypv(thread->init_function, init_function);
675 thread->init_function = sv_dup(init_function, &clone_param);
676 if (SvREFCNT(thread->init_function) == 0) {
677 SvREFCNT_inc_void(thread->init_function);
681 thread->params = sv_dup(params, &clone_param);
682 SvREFCNT_inc_void(thread->params);
684 /* The code below checks that anything living on the tmps stack and
685 * has been cloned (so it lives in the ptr_table) has a refcount
688 * If the refcount is 0 it means that a something on the stack/context
689 * was holding a reference to it and since we init_stacks() in
690 * perl_clone that won't get cleaned and we will get a leaked scalar.
691 * The reason it was cloned was that it lived on the @_ stack.
693 * Example of this can be found in bugreport 15837 where calls in the
694 * parameter list end up as a temp.
696 * One could argue that this fix should be in perl_clone.
698 while (tmps_ix > 0) {
699 SV* sv = (SV*)ptr_table_fetch(PL_ptr_table, tmps_tmp[tmps_ix]);
701 if (sv && SvREFCNT(sv) == 0) {
702 SvREFCNT_inc_void(sv);
707 SvTEMP_off(thread->init_function);
708 ptr_table_free(PL_ptr_table);
710 PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
712 S_ithread_set(aTHX_ current_thread);
713 PERL_SET_CONTEXT(aTHX);
715 /* Create/start the thread */
717 thread->handle = CreateThread(NULL,
718 (DWORD)thread->stack_size,
721 STACK_SIZE_PARAM_IS_A_RESERVATION,
725 STATIC pthread_attr_t attr;
726 STATIC int attr_inited = 0;
727 STATIC int attr_joinable = PTHREAD_CREATE_JOINABLE;
729 pthread_attr_init(&attr);
733 # ifdef PTHREAD_ATTR_SETDETACHSTATE
734 /* Threads start out joinable */
735 PTHREAD_ATTR_SETDETACHSTATE(&attr, attr_joinable);
738 # ifdef _POSIX_THREAD_ATTR_STACKSIZE
739 /* Set thread's stack size */
740 if (thread->stack_size > 0) {
741 rc_stack_size = pthread_attr_setstacksize(&attr, (size_t)thread->stack_size);
745 /* Create the thread */
746 if (! rc_stack_size) {
747 # ifdef OLD_PTHREADS_API
748 rc_thread_create = pthread_create(&thread->thr,
753 # if defined(HAS_PTHREAD_ATTR_SETSCOPE) && defined(PTHREAD_SCOPE_SYSTEM)
754 pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);
756 rc_thread_create = pthread_create(&thread->thr,
763 # ifdef _POSIX_THREAD_ATTR_STACKSIZE
764 /* Try to get thread's actual stack size */
768 stacksize = pthread_attr_getstacksize(attr);
770 if (! pthread_attr_getstacksize(&attr, &stacksize))
773 thread->stack_size = (IV)stacksize;
780 /* Check for errors */
782 if (thread->handle == NULL) {
784 if (rc_stack_size || rc_thread_create) {
786 /* Must unlock mutex for destruct call */
787 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
789 thread->state |= PERL_ITHR_NONVIABLE;
790 S_ithread_destruct(aTHX_ thread);
792 if (ckWARN_d(WARN_THREADS)) {
794 Perl_warn(aTHX_ "Thread creation failed: pthread_attr_setstacksize(%" IVdf ") returned %d", thread->stack_size, rc_stack_size);
796 Perl_warn(aTHX_ "Thread creation failed: pthread_create returned %d", rc_thread_create);
803 MY_POOL.running_threads++;
808 #endif /* USE_ITHREADS */
811 MODULE = threads PACKAGE = threads PREFIX = ithread_
821 SV *function_to_call;
827 SV *thread_exit_only;
833 if ((items >= 2) && SvROK(ST(1)) && SvTYPE(SvRV(ST(1)))==SVt_PVHV) {
835 Perl_croak(aTHX_ "Usage: threads->create(\\%specs, function, ...)");
837 specs = (HV*)SvRV(ST(1));
841 Perl_croak(aTHX_ "Usage: threads->create(function, ...)");
847 if (sv_isobject(ST(0))) {
849 classname = HvNAME(SvSTASH(SvRV(ST(0))));
850 thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
851 MUTEX_LOCK(&thread->mutex);
852 stack_size = thread->stack_size;
853 exit_opt = thread->state & PERL_ITHR_THREAD_EXIT_ONLY;
854 MUTEX_UNLOCK(&thread->mutex);
856 /* threads->create() */
857 classname = (char *)SvPV_nolen(ST(0));
858 stack_size = MY_POOL.default_stack_size;
859 thread_exit_only = get_sv("threads::thread_exit_only", TRUE);
860 exit_opt = (SvTRUE(thread_exit_only))
861 ? PERL_ITHR_THREAD_EXIT_ONLY : 0;
864 function_to_call = ST(idx+1);
869 if (hv_exists(specs, "stack", 5)) {
870 stack_size = SvIV(*hv_fetch(specs, "stack", 5, 0));
871 } else if (hv_exists(specs, "stacksize", 9)) {
872 stack_size = SvIV(*hv_fetch(specs, "stacksize", 9, 0));
873 } else if (hv_exists(specs, "stack_size", 10)) {
874 stack_size = SvIV(*hv_fetch(specs, "stack_size", 10, 0));
878 if (hv_exists(specs, "context", 7)) {
879 str = (char *)SvPV_nolen(*hv_fetch(specs, "context", 7, 0));
894 Perl_croak(aTHX_ "Invalid context: %s", str);
896 } else if (hv_exists(specs, "array", 5)) {
897 if (SvTRUE(*hv_fetch(specs, "array", 5, 0))) {
900 } else if (hv_exists(specs, "scalar", 6)) {
901 if (SvTRUE(*hv_fetch(specs, "scalar", 6, 0))) {
904 } else if (hv_exists(specs, "void", 4)) {
905 if (SvTRUE(*hv_fetch(specs, "void", 4, 0))) {
910 /* exit => thread_only */
911 if (hv_exists(specs, "exit", 4)) {
912 str = (char *)SvPV_nolen(*hv_fetch(specs, "exit", 4, 0));
913 exit_opt = (*str == 't' || *str == 'T')
914 ? PERL_ITHR_THREAD_EXIT_ONLY : 0;
918 context = GIMME_V; /* Implicit context */
920 context |= (GIMME_V & (~(G_ARRAY|G_SCALAR|G_VOID)));
926 for (ii=2; ii < items ; ii++) {
927 av_push(params, SvREFCNT_inc(ST(idx+ii)));
932 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
933 thread = S_ithread_create(aTHX_ function_to_call,
937 newRV_noinc((SV*)params));
939 XSRETURN_UNDEF; /* Mutex already unlocked */
941 ST(0) = sv_2mortal(S_ithread_to_SV(aTHX_ Nullsv, thread, classname, FALSE));
942 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
945 MUTEX_UNLOCK(&thread->mutex);
947 /* XSRETURN(1); - implied */
957 int want_running = 0;
961 /* Class method only */
963 Perl_croak(aTHX_ "Usage: threads->list(...)");
965 classname = (char *)SvPV_nolen(ST(0));
967 /* Calling context */
968 list_context = (GIMME_V == G_ARRAY);
970 /* Running or joinable parameter */
972 want_running = SvTRUE(ST(1));
975 /* Walk through threads list */
976 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
977 for (thread = MY_POOL.main_thread.next;
978 thread != &MY_POOL.main_thread;
979 thread = thread->next)
981 MUTEX_LOCK(&thread->mutex);
982 state = thread->state;
983 MUTEX_UNLOCK(&thread->mutex);
985 /* Ignore detached or joined threads */
986 if (state & PERL_ITHR_UNCALLABLE) {
990 /* Filter per parameter */
993 if (state & PERL_ITHR_FINISHED) {
994 continue; /* Not running */
997 if (! (state & PERL_ITHR_FINISHED)) {
998 continue; /* Still running - not joinable yet */
1003 /* Push object on stack if list context */
1005 XPUSHs(sv_2mortal(S_ithread_to_SV(aTHX_ Nullsv, thread, classname, TRUE)));
1009 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
1010 /* If scalar context, send back count */
1011 if (! list_context) {
1022 /* Class method only */
1023 if ((items != 1) || SvROK(ST(0))) {
1024 Perl_croak(aTHX_ "Usage: threads->self()");
1026 classname = (char *)SvPV_nolen(ST(0));
1028 thread = S_ithread_get(aTHX);
1030 ST(0) = sv_2mortal(S_ithread_to_SV(aTHX_ Nullsv, thread, classname, TRUE));
1031 /* XSRETURN(1); - implied */
1039 PERL_UNUSED_VAR(items);
1040 thread = S_SV_to_ithread(aTHX_ ST(0));
1041 XST_mUV(0, thread->tid);
1042 /* XSRETURN(1); - implied */
1049 ithread *current_thread;
1062 /* Object method only */
1063 if ((items != 1) || ! sv_isobject(ST(0))) {
1064 Perl_croak(aTHX_ "Usage: $thr->join()");
1067 /* Check if the thread is joinable and not ourselves */
1068 thread = S_SV_to_ithread(aTHX_ ST(0));
1069 current_thread = S_ithread_get(aTHX);
1071 MUTEX_LOCK(&thread->mutex);
1072 if ((join_err = (thread->state & PERL_ITHR_UNCALLABLE))) {
1073 MUTEX_UNLOCK(&thread->mutex);
1074 Perl_croak(aTHX_ (join_err & PERL_ITHR_DETACHED)
1075 ? "Cannot join a detached thread"
1076 : "Thread already joined");
1077 } else if (thread->tid == current_thread->tid) {
1078 MUTEX_UNLOCK(&thread->mutex);
1079 Perl_croak(aTHX_ "Cannot join self");
1082 /* Mark as joined */
1083 thread->state |= PERL_ITHR_JOINED;
1084 MUTEX_UNLOCK(&thread->mutex);
1086 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
1087 MY_POOL.joinable_threads--;
1088 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
1090 /* Join the thread */
1092 if (WaitForSingleObject(thread->handle, INFINITE) != WAIT_OBJECT_0) {
1093 /* Timeout/abandonment unexpected here; check $^E */
1094 Perl_croak(aTHX_ "PANIC: underlying join failed");
1097 if ((rc_join = pthread_join(thread->thr, &retval)) != 0) {
1098 /* In progress/deadlock/unknown unexpected here; check $! */
1100 Perl_croak(aTHX_ "PANIC: underlying join failed");
1104 MUTEX_LOCK(&thread->mutex);
1105 /* Get the return value from the call_sv */
1106 /* Objects do not survive this process - FIXME */
1109 PerlInterpreter *other_perl;
1110 CLONE_PARAMS clone_params;
1112 params_copy = (AV *)SvRV(thread->params);
1113 other_perl = thread->interp;
1114 clone_params.stashes = newAV();
1115 clone_params.flags = CLONEf_JOIN_IN;
1116 PL_ptr_table = ptr_table_new();
1117 S_ithread_set(aTHX_ thread);
1118 /* Ensure 'meaningful' addresses retain their meaning */
1119 ptr_table_store(PL_ptr_table, &other_perl->Isv_undef, &PL_sv_undef);
1120 ptr_table_store(PL_ptr_table, &other_perl->Isv_no, &PL_sv_no);
1121 ptr_table_store(PL_ptr_table, &other_perl->Isv_yes, &PL_sv_yes);
1122 params = (AV *)sv_dup((SV*)params_copy, &clone_params);
1123 S_ithread_set(aTHX_ current_thread);
1124 SvREFCNT_dec(clone_params.stashes);
1125 SvREFCNT_inc_void(params);
1126 ptr_table_free(PL_ptr_table);
1127 PL_ptr_table = NULL;
1130 /* If thread didn't die, then we can free its interpreter */
1131 if (! (thread->state & PERL_ITHR_DIED)) {
1132 S_ithread_clear(aTHX_ thread);
1134 MUTEX_UNLOCK(&thread->mutex);
1136 /* Try to cleanup thread */
1137 S_ithread_destruct(aTHX_ thread);
1139 /* If no return values, then just return */
1144 /* Put return values on stack */
1145 len = (int)AvFILL(params);
1146 for (ii=0; ii <= len; ii++) {
1147 SV* param = av_shift(params);
1148 XPUSHs(sv_2mortal(param));
1151 /* Free return value array */
1152 SvREFCNT_dec(params);
1158 PERL_UNUSED_VAR(items);
1169 PERL_UNUSED_VAR(items);
1171 /* Detach the thread */
1172 thread = S_SV_to_ithread(aTHX_ ST(0));
1173 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
1174 MUTEX_LOCK(&thread->mutex);
1175 if (! (detach_err = (thread->state & PERL_ITHR_UNCALLABLE))) {
1176 /* Thread is detachable */
1177 thread->state |= PERL_ITHR_DETACHED;
1179 /* Windows has no 'detach thread' function */
1181 PERL_THREAD_DETACH(thread->thr);
1183 if (thread->state & PERL_ITHR_FINISHED) {
1184 MY_POOL.joinable_threads--;
1186 MY_POOL.running_threads--;
1187 MY_POOL.detached_threads++;
1190 MUTEX_UNLOCK(&thread->mutex);
1191 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
1194 Perl_croak(aTHX_ (detach_err & PERL_ITHR_DETACHED)
1195 ? "Thread already detached"
1196 : "Cannot detach a joined thread");
1199 /* If thread is finished and didn't die,
1200 * then we can free its interpreter */
1201 MUTEX_LOCK(&thread->mutex);
1202 if ((thread->state & PERL_ITHR_FINISHED) &&
1203 ! (thread->state & PERL_ITHR_DIED))
1205 S_ithread_clear(aTHX_ thread);
1207 MUTEX_UNLOCK(&thread->mutex);
1209 /* Try to cleanup thread */
1210 S_ithread_destruct(aTHX_ thread);
1220 /* Must have safe signals */
1221 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG) {
1222 Perl_croak(aTHX_ "Cannot signal threads without safe signals");
1225 /* Object method only */
1226 if ((items != 2) || ! sv_isobject(ST(0))) {
1227 Perl_croak(aTHX_ "Usage: $thr->kill('SIG...')");
1231 sig_name = SvPV_nolen(ST(1));
1232 if (isALPHA(*sig_name)) {
1233 if (*sig_name == 'S' && sig_name[1] == 'I' && sig_name[2] == 'G') {
1236 if ((signal = whichsig(sig_name)) < 0) {
1237 Perl_croak(aTHX_ "Unrecognized signal name: %s", sig_name);
1240 signal = SvIV(ST(1));
1243 /* Set the signal for the thread */
1244 thread = S_SV_to_ithread(aTHX_ ST(0));
1245 MUTEX_LOCK(&thread->mutex);
1246 if (thread->interp) {
1247 dTHXa(thread->interp);
1248 PL_psig_pend[signal]++;
1251 MUTEX_UNLOCK(&thread->mutex);
1253 /* Return the thread to allow for method chaining */
1255 /* XSRETURN(1); - implied */
1259 ithread_DESTROY(...)
1261 PERL_UNUSED_VAR(items);
1262 sv_unmagic(SvRV(ST(0)), PERL_MAGIC_shared_scalar);
1270 PERL_UNUSED_VAR(items);
1272 /* Compares TIDs to determine thread equality */
1273 if (sv_isobject(ST(0)) && sv_isobject(ST(1))) {
1274 ithread *thr1 = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1275 ithread *thr2 = INT2PTR(ithread *, SvIV(SvRV(ST(1))));
1276 are_equal = (thr1->tid == thr2->tid);
1281 /* Return 0 on false for backward compatibility */
1284 /* XSRETURN(1); - implied */
1297 /* Class method only */
1299 Perl_croak(aTHX_ "Usage: threads->object($tid)");
1301 classname = (char *)SvPV_nolen(ST(0));
1303 if ((items < 2) || ! SvOK(ST(1))) {
1307 /* threads->object($tid) */
1310 /* Walk through threads list */
1311 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
1312 for (thread = MY_POOL.main_thread.next;
1313 thread != &MY_POOL.main_thread;
1314 thread = thread->next)
1317 if (thread->tid == tid) {
1318 /* Ignore if detached or joined */
1319 MUTEX_LOCK(&thread->mutex);
1320 state = thread->state;
1321 MUTEX_UNLOCK(&thread->mutex);
1322 if (! (state & PERL_ITHR_UNCALLABLE)) {
1323 /* Put object on stack */
1324 ST(0) = sv_2mortal(S_ithread_to_SV(aTHX_ Nullsv, thread, classname, TRUE));
1330 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
1335 /* XSRETURN(1); - implied */
1339 ithread__handle(...);
1343 PERL_UNUSED_VAR(items);
1344 thread = S_SV_to_ithread(aTHX_ ST(0));
1346 XST_mUV(0, PTR2UV(&thread->handle));
1348 XST_mUV(0, PTR2UV(&thread->thr));
1350 /* XSRETURN(1); - implied */
1354 ithread_get_stack_size(...)
1359 PERL_UNUSED_VAR(items);
1360 if (sv_isobject(ST(0))) {
1361 /* $thr->get_stack_size() */
1362 ithread *thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1363 stack_size = thread->stack_size;
1365 /* threads->get_stack_size() */
1366 stack_size = MY_POOL.default_stack_size;
1368 XST_mIV(0, stack_size);
1369 /* XSRETURN(1); - implied */
1373 ithread_set_stack_size(...)
1379 Perl_croak(aTHX_ "Usage: threads->set_stack_size($size)");
1381 if (sv_isobject(ST(0))) {
1382 Perl_croak(aTHX_ "Cannot change stack size of an existing thread");
1385 old_size = MY_POOL.default_stack_size;
1386 MY_POOL.default_stack_size = S_good_stack_size(aTHX_ SvIV(ST(1)));
1387 XST_mIV(0, old_size);
1388 /* XSRETURN(1); - implied */
1392 ithread_is_running(...)
1396 /* Object method only */
1397 if ((items != 1) || ! sv_isobject(ST(0))) {
1398 Perl_croak(aTHX_ "Usage: $thr->is_running()");
1401 thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1402 MUTEX_LOCK(&thread->mutex);
1403 ST(0) = (thread->state & PERL_ITHR_FINISHED) ? &PL_sv_no : &PL_sv_yes;
1404 MUTEX_UNLOCK(&thread->mutex);
1405 /* XSRETURN(1); - implied */
1409 ithread_is_detached(...)
1413 PERL_UNUSED_VAR(items);
1414 thread = S_SV_to_ithread(aTHX_ ST(0));
1415 MUTEX_LOCK(&thread->mutex);
1416 ST(0) = (thread->state & PERL_ITHR_DETACHED) ? &PL_sv_yes : &PL_sv_no;
1417 MUTEX_UNLOCK(&thread->mutex);
1418 /* XSRETURN(1); - implied */
1422 ithread_is_joinable(...)
1426 /* Object method only */
1427 if ((items != 1) || ! sv_isobject(ST(0))) {
1428 Perl_croak(aTHX_ "Usage: $thr->is_joinable()");
1431 thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1432 MUTEX_LOCK(&thread->mutex);
1433 ST(0) = ((thread->state & PERL_ITHR_FINISHED) &&
1434 ! (thread->state & PERL_ITHR_UNCALLABLE))
1435 ? &PL_sv_yes : &PL_sv_no;
1436 MUTEX_UNLOCK(&thread->mutex);
1437 /* XSRETURN(1); - implied */
1441 ithread_wantarray(...)
1445 PERL_UNUSED_VAR(items);
1446 thread = S_SV_to_ithread(aTHX_ ST(0));
1447 ST(0) = (thread->gimme & G_ARRAY) ? &PL_sv_yes :
1448 (thread->gimme & G_VOID) ? &PL_sv_undef
1449 /* G_SCALAR */ : &PL_sv_no;
1450 /* XSRETURN(1); - implied */
1454 ithread_set_thread_exit_only(...)
1459 Perl_croak(aTHX_ "Usage: ->set_thread_exit_only(boolean)");
1461 thread = S_SV_to_ithread(aTHX_ ST(0));
1462 MUTEX_LOCK(&thread->mutex);
1463 if (SvTRUE(ST(1))) {
1464 thread->state |= PERL_ITHR_THREAD_EXIT_ONLY;
1466 thread->state &= ~PERL_ITHR_THREAD_EXIT_ONLY;
1468 MUTEX_UNLOCK(&thread->mutex);
1477 /* Object method only */
1478 if ((items != 1) || ! sv_isobject(ST(0))) {
1479 Perl_croak(aTHX_ "Usage: $thr->err()");
1482 thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1483 MUTEX_LOCK(&thread->mutex);
1485 /* If thread died, then clone the error into the calling thread */
1486 if (thread->state & PERL_ITHR_DIED) {
1487 PerlInterpreter *other_perl;
1488 CLONE_PARAMS clone_params;
1489 ithread *current_thread;
1491 other_perl = thread->interp;
1492 clone_params.stashes = newAV();
1493 clone_params.flags = CLONEf_JOIN_IN;
1494 PL_ptr_table = ptr_table_new();
1495 current_thread = S_ithread_get(aTHX);
1496 S_ithread_set(aTHX_ thread);
1497 /* Ensure 'meaningful' addresses retain their meaning */
1498 ptr_table_store(PL_ptr_table, &other_perl->Isv_undef, &PL_sv_undef);
1499 ptr_table_store(PL_ptr_table, &other_perl->Isv_no, &PL_sv_no);
1500 ptr_table_store(PL_ptr_table, &other_perl->Isv_yes, &PL_sv_yes);
1501 err = sv_dup(thread->err, &clone_params);
1502 S_ithread_set(aTHX_ current_thread);
1503 SvREFCNT_dec(clone_params.stashes);
1504 SvREFCNT_inc_void(err);
1505 /* If error was an object, bless it into the correct class */
1506 if (thread->err_class) {
1507 sv_bless(err, gv_stashpv(thread->err_class, 1));
1509 ptr_table_free(PL_ptr_table);
1510 PL_ptr_table = NULL;
1513 MUTEX_UNLOCK(&thread->mutex);
1519 ST(0) = sv_2mortal(err);
1520 /* XSRETURN(1); - implied */
1523 #endif /* USE_ITHREADS */
1529 SV *my_pool_sv = *hv_fetch(PL_modglobal, MY_POOL_KEY,
1530 sizeof(MY_POOL_KEY)-1, TRUE);
1531 my_pool_t *my_poolp = (my_pool_t*)SvPVX(newSV(sizeof(my_pool_t)-1));
1535 Zero(my_poolp, 1, my_pool_t);
1536 sv_setuv(my_pool_sv, PTR2UV(my_poolp));
1538 PL_perl_destruct_level = 2;
1539 MUTEX_INIT(&MY_POOL.create_destruct_mutex);
1540 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
1542 PL_threadhook = &Perl_ithread_hook;
1544 MY_POOL.tid_counter = 1;
1545 # ifdef THREAD_CREATE_NEEDS_STACK
1546 MY_POOL.default_stack_size = THREAD_CREATE_NEEDS_STACK;
1549 /* The 'main' thread is thread 0.
1550 * It is detached (unjoinable) and immortal.
1553 MUTEX_INIT(&MY_POOL.main_thread.mutex);
1555 /* Head of the threads list */
1556 MY_POOL.main_thread.next = &MY_POOL.main_thread;
1557 MY_POOL.main_thread.prev = &MY_POOL.main_thread;
1559 MY_POOL.main_thread.count = 1; /* Immortal */
1561 MY_POOL.main_thread.interp = aTHX;
1562 MY_POOL.main_thread.state = PERL_ITHR_DETACHED; /* Detached */
1563 MY_POOL.main_thread.stack_size = MY_POOL.default_stack_size;
1565 MY_POOL.main_thread.thr = GetCurrentThreadId();
1567 MY_POOL.main_thread.thr = pthread_self();
1570 S_ithread_set(aTHX_ &MY_POOL.main_thread);
1571 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
1572 #endif /* USE_ITHREADS */