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_JOINABLE 0
49 #define PERL_ITHR_DETACHED 1
50 #define PERL_ITHR_JOINED 2
51 #define PERL_ITHR_FINISHED 4
52 #define PERL_ITHR_THREAD_EXIT_ONLY 8
54 typedef struct _ithread {
55 struct _ithread *next; /* Next thread in the list */
56 struct _ithread *prev; /* Prev thread in the list */
57 PerlInterpreter *interp; /* The threads interpreter */
58 UV tid; /* Threads module's thread id */
59 perl_mutex mutex; /* Mutex for updating things in this struct */
60 int count; /* How many SVs have a reference to us */
61 int state; /* Detached, joined, finished, etc. */
62 int gimme; /* Context of create */
63 SV *init_function; /* Code to run */
64 SV *params; /* Args to pass function */
66 DWORD thr; /* OS's idea if thread id */
67 HANDLE handle; /* OS's waitable handle */
69 pthread_t thr; /* OS's handle for the thread */
75 /* Used by Perl interpreter for thread context switching */
76 #define MY_CXT_KEY "threads::_guts" XS_VERSION
85 /* Linked list of all threads */
86 static ithread *threads;
88 /* Protects the creation and destruction of threads*/
89 static perl_mutex create_destruct_mutex;
91 static UV tid_counter = 0;
92 static IV joinable_threads = 0;
93 static IV running_threads = 0;
94 static IV detached_threads = 0;
95 #ifdef THREAD_CREATE_NEEDS_STACK
96 static IV default_stack_size = THREAD_CREATE_NEEDS_STACK;
98 static IV default_stack_size = 0;
100 static IV page_size = 0;
103 /* Used by Perl interpreter for thread context switching */
105 S_ithread_set(pTHX_ ithread *thread)
108 MY_CXT.thread = thread;
115 return (MY_CXT.thread);
119 /* Free any data (such as the Perl interpreter) attached to an ithread
120 * structure. This is a bit like undef on SVs, where the SV isn't freed,
121 * but the PVX is. Must be called with thread->mutex already held.
124 S_ithread_clear(pTHX_ ithread *thread)
126 PerlInterpreter *interp;
128 assert((thread->state & PERL_ITHR_FINISHED) &&
129 (thread->state & (PERL_ITHR_DETACHED|PERL_ITHR_JOINED)));
131 interp = thread->interp;
135 PERL_SET_CONTEXT(interp);
136 S_ithread_set(aTHX_ thread);
138 SvREFCNT_dec(thread->params);
139 thread->params = Nullsv;
141 perl_destruct(interp);
143 thread->interp = NULL;
146 PERL_SET_CONTEXT(aTHX);
150 /* Free an ithread structure and any attached data if its count == 0 */
152 S_ithread_destruct(pTHX_ ithread *thread)
157 /* Thread is still in use */
158 if (thread->count != 0) {
162 /* Main thread (0) is immortal and should never get here */
163 assert(thread->tid != 0);
165 /* Remove from circular list of threads */
166 MUTEX_LOCK(&create_destruct_mutex);
167 thread->next->prev = thread->prev;
168 thread->prev->next = thread->next;
171 MUTEX_UNLOCK(&create_destruct_mutex);
173 /* Thread is now disowned */
174 MUTEX_LOCK(&thread->mutex);
175 S_ithread_clear(aTHX_ thread);
178 handle = thread->handle;
179 thread->handle = NULL;
181 MUTEX_UNLOCK(&thread->mutex);
182 MUTEX_DESTROY(&thread->mutex);
189 /* Call PerlMemShared_free() in the context of the "first" interpreter
190 * per http://www.nntp.perl.org/group/perl.perl5.porters/110772
193 PerlMemShared_free(thread);
197 /* Warn if exiting with any unjoined threads */
203 MUTEX_LOCK(&create_destruct_mutex);
204 veto_cleanup = (running_threads || joinable_threads);
205 MUTEX_UNLOCK(&create_destruct_mutex);
208 if (ckWARN_d(WARN_THREADS)) {
209 Perl_warn(aTHX_ "Perl exited with active threads:\n\t%"
210 IVdf " running and unjoined\n\t%"
211 IVdf " finished and unjoined\n\t%"
212 IVdf " running and detached\n",
219 return (veto_cleanup);
222 /* Called on exit from main thread */
224 Perl_ithread_hook(pTHX)
226 return ((aTHX == PL_curinterp) ? S_exit_warning(aTHX) : 0);
230 /* MAGIC (in mg.h sense) hooks */
233 ithread_mg_get(pTHX_ SV *sv, MAGIC *mg)
235 ithread *thread = (ithread *)mg->mg_ptr;
236 SvIV_set(sv, PTR2IV(thread));
242 ithread_mg_free(pTHX_ SV *sv, MAGIC *mg)
244 ithread *thread = (ithread *)mg->mg_ptr;
247 MUTEX_LOCK(&thread->mutex);
248 cleanup = ((--thread->count == 0) &&
249 (thread->state & PERL_ITHR_FINISHED) &&
250 (thread->state & (PERL_ITHR_DETACHED|PERL_ITHR_JOINED)));
251 MUTEX_UNLOCK(&thread->mutex);
254 S_ithread_destruct(aTHX_ thread);
259 ithread_mg_dup(pTHX_ MAGIC *mg, CLONE_PARAMS *param)
261 ithread *thread = (ithread *)mg->mg_ptr;
262 MUTEX_LOCK(&thread->mutex);
264 MUTEX_UNLOCK(&thread->mutex);
268 MGVTBL ithread_vtbl = {
269 ithread_mg_get, /* get */
273 ithread_mg_free, /* free */
275 ithread_mg_dup /* dup */
279 /* Provided default, minimum and rational stack sizes */
281 good_stack_size(pTHX_ IV stack_size)
283 /* Use default stack size if no stack size specified */
285 return (default_stack_size);
287 #ifdef PTHREAD_STACK_MIN
288 /* Can't use less than minimum */
289 if (stack_size < PTHREAD_STACK_MIN) {
290 if (ckWARN(WARN_THREADS)) {
291 Perl_warn(aTHX_ "Using minimum thread stack size of %" IVdf, (IV)PTHREAD_STACK_MIN);
293 return (PTHREAD_STACK_MIN);
297 /* Round up to page size boundary */
298 if (page_size <= 0) {
299 #if defined(HAS_SYSCONF) && (defined(_SC_PAGESIZE) || defined(_SC_MMAP_PAGE_SIZE))
300 SETERRNO(0, SS_NORMAL);
302 page_size = sysconf(_SC_PAGESIZE);
304 page_size = sysconf(_SC_MMAP_PAGE_SIZE);
306 if ((long)page_size < 0) {
308 SV * const error = get_sv("@", FALSE);
309 (void)SvUPGRADE(error, SVt_PV);
310 Perl_croak(aTHX_ "PANIC: sysconf: %s", SvPV_nolen(error));
312 Perl_croak(aTHX_ "PANIC: sysconf: pagesize unknown");
316 # ifdef HAS_GETPAGESIZE
317 page_size = getpagesize();
319 # if defined(I_SYS_PARAM) && defined(PAGESIZE)
320 page_size = PAGESIZE;
322 page_size = 8192; /* A conservative default */
326 Perl_croak(aTHX_ "PANIC: bad pagesize %" IVdf, (IV)page_size);
329 stack_size = ((stack_size + (page_size - 1)) / page_size) * page_size;
335 /* Starts executing the thread.
336 * Passed as the C level function to run in the new thread.
339 static THREAD_RET_TYPE
340 S_ithread_run(LPVOID arg)
343 S_ithread_run(void * arg)
346 ithread *thread = (ithread *)arg;
355 dTHXa(thread->interp);
357 /* Blocked until ->create() call finishes */
358 MUTEX_LOCK(&thread->mutex);
359 MUTEX_UNLOCK(&thread->mutex);
361 PERL_SET_CONTEXT(thread->interp);
362 S_ithread_set(aTHX_ thread);
364 PL_perl_destruct_level = 2;
367 AV *params = (AV *)SvRV(thread->params);
368 int len = (int)av_len(params)+1;
375 /* Put args on the stack */
377 for (ii=0; ii < len; ii++) {
378 XPUSHs(av_shift(params));
382 oldscope = PL_scopestack_ix;
385 /* Run the specified function */
386 len = (int)call_sv(thread->init_function, thread->gimme|G_EVAL);
387 } else if (jmp_rc == 2) {
390 exit_code = STATUS_CURRENT;
391 while (PL_scopestack_ix > oldscope) {
397 /* Remove args from stack and put back in params array */
399 for (ii=len-1; ii >= 0; ii--) {
402 av_store(params, ii, SvREFCNT_inc(sv));
409 /* Check for failure */
410 if (SvTRUE(ERRSV) && ckWARN_d(WARN_THREADS)) {
411 oldscope = PL_scopestack_ix;
414 /* Warn that thread died */
415 Perl_warn(aTHX_ "Thread %" UVuf " terminated abnormally: %" SVf, thread->tid, ERRSV);
416 } else if (jmp_rc == 2) {
417 /* Warn handler exited */
419 exit_code = STATUS_CURRENT;
420 while (PL_scopestack_ix > oldscope) {
427 /* Release function ref */
428 SvREFCNT_dec(thread->init_function);
429 thread->init_function = Nullsv;
432 PerlIO_flush((PerlIO *)NULL);
434 MUTEX_LOCK(&create_destruct_mutex);
435 MUTEX_LOCK(&thread->mutex);
436 /* Mark as finished */
437 thread->state |= PERL_ITHR_FINISHED;
438 /* Clear exit flag if required */
439 if (thread->state & PERL_ITHR_THREAD_EXIT_ONLY)
441 /* Cleanup if detached */
442 cleanup = (thread->state & PERL_ITHR_DETACHED);
443 MUTEX_UNLOCK(&thread->mutex);
445 /* Adjust thread status counts */
452 MUTEX_UNLOCK(&create_destruct_mutex);
454 /* Exit application if required */
456 oldscope = PL_scopestack_ix;
459 /* Warn if there are unjoined threads */
460 S_exit_warning(aTHX);
461 } else if (jmp_rc == 2) {
462 /* Warn handler exited */
463 exit_code = STATUS_CURRENT;
464 while (PL_scopestack_ix > oldscope) {
473 /* Clean up detached thread */
475 S_ithread_destruct(aTHX_ thread);
485 /* Type conversion helper functions */
487 ithread_to_SV(pTHX_ SV *obj, ithread *thread, char *classname, bool inc)
492 /* If incrementing thread ref count, then call within mutex lock */
494 MUTEX_LOCK(&thread->mutex);
496 MUTEX_UNLOCK(&thread->mutex);
503 sv = newSVrv(obj, classname);
504 sv_setiv(sv, PTR2IV(thread));
505 mg = sv_magicext(sv, Nullsv, PERL_MAGIC_shared_scalar, &ithread_vtbl, (char *)thread, 0);
506 mg->mg_flags |= MGf_DUP;
513 SV_to_ithread(pTHX_ SV *sv)
515 /* Argument is a thread */
517 return (INT2PTR(ithread *, SvIV(SvRV(sv))));
519 /* Argument is classname, therefore return current thread */
520 return (S_ithread_get(aTHX));
525 * Called in context of parent thread.
526 * Called with create_destruct_mutex locked. (Unlocked on error.)
530 pTHX_ SV *init_function,
537 CLONE_PARAMS clone_param;
538 ithread *current_thread = S_ithread_get(aTHX);
540 SV **tmps_tmp = PL_tmps_stack;
541 IV tmps_ix = PL_tmps_ix;
543 int rc_stack_size = 0;
544 int rc_thread_create = 0;
547 /* Allocate thread structure */
548 thread = (ithread *)PerlMemShared_malloc(sizeof(ithread));
550 MUTEX_UNLOCK(&create_destruct_mutex);
551 PerlLIO_write(PerlIO_fileno(Perl_error_log), PL_no_mem, strlen(PL_no_mem));
554 Zero(thread, 1, ithread);
556 /* Add to threads list */
557 thread->next = threads;
558 thread->prev = threads->prev;
559 threads->prev = thread;
560 thread->prev->next = thread;
562 /* Set count to 1 immediately in case thread exits before
563 * we return to caller!
567 /* Block new thread until ->create() call finishes */
568 MUTEX_INIT(&thread->mutex);
569 MUTEX_LOCK(&thread->mutex);
571 thread->tid = tid_counter++;
572 thread->stack_size = good_stack_size(aTHX_ stack_size);
573 thread->gimme = gimme;
574 thread->state = exit_opt;
576 /* "Clone" our interpreter into the thread's interpreter.
577 * This gives thread access to "static data" and code.
579 PerlIO_flush((PerlIO *)NULL);
580 S_ithread_set(aTHX_ thread);
582 SAVEBOOL(PL_srand_called); /* Save this so it becomes the correct value */
583 PL_srand_called = FALSE; /* Set it to false so we can detect if it gets
584 set during the clone */
587 thread->interp = perl_clone(aTHX, CLONEf_KEEP_PTR_TABLE | CLONEf_CLONE_HOST);
589 thread->interp = perl_clone(aTHX, CLONEf_KEEP_PTR_TABLE);
592 /* perl_clone() leaves us in new interpreter's context. As it is tricky
593 * to spot an implicit aTHX, create a new scope with aTHX matching the
594 * context for the duration of our work for new interpreter.
597 dTHXa(thread->interp);
601 /* Here we remove END blocks since they should only run in the thread
604 SvREFCNT_dec(PL_endav);
607 if (SvPOK(init_function)) {
608 thread->init_function = newSV(0);
609 sv_copypv(thread->init_function, init_function);
611 clone_param.flags = 0;
612 thread->init_function = sv_dup(init_function, &clone_param);
613 if (SvREFCNT(thread->init_function) == 0) {
614 SvREFCNT_inc_void(thread->init_function);
618 thread->params = sv_dup(params, &clone_param);
619 SvREFCNT_inc_void(thread->params);
621 /* The code below checks that anything living on the tmps stack and
622 * has been cloned (so it lives in the ptr_table) has a refcount
625 * If the refcount is 0 it means that a something on the stack/context
626 * was holding a reference to it and since we init_stacks() in
627 * perl_clone that won't get cleaned and we will get a leaked scalar.
628 * The reason it was cloned was that it lived on the @_ stack.
630 * Example of this can be found in bugreport 15837 where calls in the
631 * parameter list end up as a temp.
633 * One could argue that this fix should be in perl_clone.
635 while (tmps_ix > 0) {
636 SV* sv = (SV*)ptr_table_fetch(PL_ptr_table, tmps_tmp[tmps_ix]);
638 if (sv && SvREFCNT(sv) == 0) {
639 SvREFCNT_inc_void(sv);
644 SvTEMP_off(thread->init_function);
645 ptr_table_free(PL_ptr_table);
647 PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
649 S_ithread_set(aTHX_ current_thread);
650 PERL_SET_CONTEXT(aTHX);
652 /* Create/start the thread */
654 thread->handle = CreateThread(NULL,
655 (DWORD)thread->stack_size,
658 STACK_SIZE_PARAM_IS_A_RESERVATION,
662 static pthread_attr_t attr;
663 static int attr_inited = 0;
664 static int attr_joinable = PTHREAD_CREATE_JOINABLE;
666 pthread_attr_init(&attr);
670 # ifdef PTHREAD_ATTR_SETDETACHSTATE
671 /* Threads start out joinable */
672 PTHREAD_ATTR_SETDETACHSTATE(&attr, attr_joinable);
675 # ifdef _POSIX_THREAD_ATTR_STACKSIZE
676 /* Set thread's stack size */
677 if (thread->stack_size > 0) {
678 rc_stack_size = pthread_attr_setstacksize(&attr, (size_t)thread->stack_size);
682 /* Create the thread */
683 if (! rc_stack_size) {
684 # ifdef OLD_PTHREADS_API
685 rc_thread_create = pthread_create(&thread->thr,
690 # if defined(HAS_PTHREAD_ATTR_SETSCOPE) && defined(PTHREAD_SCOPE_SYSTEM)
691 pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);
693 rc_thread_create = pthread_create(&thread->thr,
700 # ifdef _POSIX_THREAD_ATTR_STACKSIZE
701 /* Try to get thread's actual stack size */
705 stacksize = pthread_attr_getstacksize(attr);
707 if (! pthread_attr_getstacksize(&attr, &stacksize))
710 thread->stack_size = (IV)stacksize;
717 /* Check for errors */
719 if (thread->handle == NULL) {
721 if (rc_stack_size || rc_thread_create) {
723 /* Must unlock mutex for destruct call */
724 MUTEX_UNLOCK(&create_destruct_mutex);
726 S_ithread_destruct(aTHX_ thread);
728 if (ckWARN_d(WARN_THREADS)) {
730 Perl_warn(aTHX_ "Thread creation failed: pthread_attr_setstacksize(%" IVdf ") returned %d", thread->stack_size, rc_stack_size);
732 Perl_warn(aTHX_ "Thread creation failed: pthread_create returned %d", rc_thread_create);
743 #endif /* USE_ITHREADS */
746 MODULE = threads PACKAGE = threads PREFIX = ithread_
756 SV *function_to_call;
762 SV *thread_exit_only;
767 if ((items >= 2) && SvROK(ST(1)) && SvTYPE(SvRV(ST(1)))==SVt_PVHV) {
769 Perl_croak(aTHX_ "Usage: threads->create(\\%specs, function, ...)");
770 specs = (HV*)SvRV(ST(1));
774 Perl_croak(aTHX_ "Usage: threads->create(function, ...)");
779 if (sv_isobject(ST(0))) {
781 classname = HvNAME(SvSTASH(SvRV(ST(0))));
782 thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
783 stack_size = thread->stack_size;
784 exit_opt = thread->state & PERL_ITHR_THREAD_EXIT_ONLY;
786 /* threads->create() */
787 classname = (char *)SvPV_nolen(ST(0));
788 stack_size = default_stack_size;
789 thread_exit_only = get_sv("threads::thread_exit_only", TRUE);
790 exit_opt = (SvTRUE(thread_exit_only))
791 ? PERL_ITHR_THREAD_EXIT_ONLY : 0;
794 function_to_call = ST(idx+1);
799 if (hv_exists(specs, "stack", 5)) {
800 stack_size = SvIV(*hv_fetch(specs, "stack", 5, 0));
801 } else if (hv_exists(specs, "stacksize", 9)) {
802 stack_size = SvIV(*hv_fetch(specs, "stacksize", 9, 0));
803 } else if (hv_exists(specs, "stack_size", 10)) {
804 stack_size = SvIV(*hv_fetch(specs, "stack_size", 10, 0));
808 if (hv_exists(specs, "context", 7)) {
809 str = (char *)SvPV_nolen(*hv_fetch(specs, "context", 7, 0));
824 Perl_croak(aTHX_ "Invalid context: %s", str);
826 } else if (hv_exists(specs, "array", 5)) {
827 if (SvTRUE(*hv_fetch(specs, "array", 5, 0))) {
830 } else if (hv_exists(specs, "scalar", 6)) {
831 if (SvTRUE(*hv_fetch(specs, "scalar", 6, 0))) {
834 } else if (hv_exists(specs, "void", 4)) {
835 if (SvTRUE(*hv_fetch(specs, "void", 4, 0))) {
840 /* exit => thread_only */
841 if (hv_exists(specs, "exit", 4)) {
842 str = (char *)SvPV_nolen(*hv_fetch(specs, "exit", 4, 0));
843 exit_opt = (*str == 't' || *str == 'T')
844 ? PERL_ITHR_THREAD_EXIT_ONLY : 0;
848 context = GIMME_V; /* Implicit context */
850 context |= (GIMME_V & (~(G_ARRAY|G_SCALAR|G_VOID)));
856 for (ii=2; ii < items ; ii++) {
857 av_push(params, SvREFCNT_inc(ST(idx+ii)));
862 MUTEX_LOCK(&create_destruct_mutex);
863 thread = S_ithread_create(aTHX_ function_to_call,
867 newRV_noinc((SV*)params));
869 XSRETURN_UNDEF; /* Mutex already unlocked */
871 ST(0) = sv_2mortal(ithread_to_SV(aTHX_ Nullsv, thread, classname, FALSE));
874 MUTEX_UNLOCK(&thread->mutex);
875 MUTEX_UNLOCK(&create_destruct_mutex);
877 /* XSRETURN(1); - implied */
889 /* Class method only */
891 Perl_croak(aTHX_ "Usage: threads->list(...)");
892 classname = (char *)SvPV_nolen(ST(0));
894 /* Calling context */
895 list_context = (GIMME_V == G_ARRAY);
897 /* Running or joinable parameter */
899 want_running = SvTRUE(ST(1));
902 /* Walk through threads list */
903 MUTEX_LOCK(&create_destruct_mutex);
904 for (thread = threads->next;
906 thread = thread->next)
908 /* Ignore detached or joined threads */
909 if (thread->state & (PERL_ITHR_DETACHED|PERL_ITHR_JOINED)) {
913 /* Filter per parameter */
916 if (thread->state & PERL_ITHR_FINISHED) {
917 continue; /* Not running */
920 if (! (thread->state & PERL_ITHR_FINISHED)) {
921 continue; /* Still running - not joinable yet */
926 /* Push object on stack if list context */
928 XPUSHs(sv_2mortal(ithread_to_SV(aTHX_ Nullsv, thread, classname, TRUE)));
932 MUTEX_UNLOCK(&create_destruct_mutex);
933 /* If scalar context, send back count */
934 if (! list_context) {
945 /* Class method only */
947 Perl_croak(aTHX_ "Usage: threads->self()");
948 classname = (char *)SvPV_nolen(ST(0));
950 thread = S_ithread_get(aTHX);
952 ST(0) = sv_2mortal(ithread_to_SV(aTHX_ Nullsv, thread, classname, TRUE));
953 /* XSRETURN(1); - implied */
961 thread = SV_to_ithread(aTHX_ ST(0));
962 XST_mUV(0, thread->tid);
963 /* XSRETURN(1); - implied */
980 /* Object method only */
981 if (! sv_isobject(ST(0)))
982 Perl_croak(aTHX_ "Usage: $thr->join()");
984 /* Check if the thread is joinable */
985 thread = SV_to_ithread(aTHX_ ST(0));
986 join_err = (thread->state & (PERL_ITHR_DETACHED|PERL_ITHR_JOINED));
988 if (join_err & PERL_ITHR_DETACHED) {
989 Perl_croak(aTHX_ "Cannot join a detached thread");
991 Perl_croak(aTHX_ "Thread already joined");
995 /* Join the thread */
997 waitcode = WaitForSingleObject(thread->handle, INFINITE);
999 pthread_join(thread->thr, &retval);
1002 MUTEX_LOCK(&thread->mutex);
1003 /* Mark as joined */
1004 thread->state |= PERL_ITHR_JOINED;
1006 /* Get the return value from the call_sv */
1009 PerlInterpreter *other_perl;
1010 CLONE_PARAMS clone_params;
1011 ithread *current_thread;
1013 params_copy = (AV *)SvRV(thread->params);
1014 other_perl = thread->interp;
1015 clone_params.stashes = newAV();
1016 clone_params.flags = CLONEf_JOIN_IN;
1017 PL_ptr_table = ptr_table_new();
1018 current_thread = S_ithread_get(aTHX);
1019 S_ithread_set(aTHX_ thread);
1020 /* Ensure 'meaningful' addresses retain their meaning */
1021 ptr_table_store(PL_ptr_table, &other_perl->Isv_undef, &PL_sv_undef);
1022 ptr_table_store(PL_ptr_table, &other_perl->Isv_no, &PL_sv_no);
1023 ptr_table_store(PL_ptr_table, &other_perl->Isv_yes, &PL_sv_yes);
1024 params = (AV *)sv_dup((SV*)params_copy, &clone_params);
1025 S_ithread_set(aTHX_ current_thread);
1026 SvREFCNT_dec(clone_params.stashes);
1027 SvREFCNT_inc_void(params);
1028 ptr_table_free(PL_ptr_table);
1029 PL_ptr_table = NULL;
1032 /* We are finished with the thread */
1033 S_ithread_clear(aTHX_ thread);
1034 MUTEX_UNLOCK(&thread->mutex);
1036 MUTEX_LOCK(&create_destruct_mutex);
1037 if (! (thread->state & PERL_ITHR_DETACHED)) {
1040 MUTEX_UNLOCK(&create_destruct_mutex);
1042 /* If no return values, then just return */
1047 /* Put return values on stack */
1048 len = (int)AvFILL(params);
1049 for (ii=0; ii <= len; ii++) {
1050 SV* param = av_shift(params);
1051 XPUSHs(sv_2mortal(param));
1054 /* Free return value array */
1055 SvREFCNT_dec(params);
1071 /* Check if the thread is detachable */
1072 thread = SV_to_ithread(aTHX_ ST(0));
1073 if ((detach_err = (thread->state & (PERL_ITHR_DETACHED|PERL_ITHR_JOINED)))) {
1074 if (detach_err & PERL_ITHR_DETACHED) {
1075 Perl_croak(aTHX_ "Thread already detached");
1077 Perl_croak(aTHX_ "Cannot detach a joined thread");
1081 /* Detach the thread */
1082 MUTEX_LOCK(&create_destruct_mutex);
1083 MUTEX_LOCK(&thread->mutex);
1084 thread->state |= PERL_ITHR_DETACHED;
1086 /* Windows has no 'detach thread' function */
1088 PERL_THREAD_DETACH(thread->thr);
1090 /* Cleanup if finished */
1091 cleanup = (thread->state & PERL_ITHR_FINISHED);
1092 MUTEX_UNLOCK(&thread->mutex);
1100 MUTEX_UNLOCK(&create_destruct_mutex);
1103 S_ithread_destruct(aTHX_ thread);
1114 /* Must have safe signals */
1115 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
1116 Perl_croak(aTHX_ "Cannot signal threads without safe signals");
1118 /* Object method only */
1119 if (! sv_isobject(ST(0)))
1120 Perl_croak(aTHX_ "Usage: $thr->kill('SIG...')");
1123 sig_name = SvPV_nolen(ST(1));
1124 if (isALPHA(*sig_name)) {
1125 if (*sig_name == 'S' && sig_name[1] == 'I' && sig_name[2] == 'G')
1127 if ((signal = whichsig(sig_name)) < 0)
1128 Perl_croak(aTHX_ "Unrecognized signal name: %s", sig_name);
1130 signal = SvIV(ST(1));
1132 /* Set the signal for the thread */
1133 thread = SV_to_ithread(aTHX_ ST(0));
1134 MUTEX_LOCK(&thread->mutex);
1135 if (thread->interp) {
1136 dTHXa(thread->interp);
1137 PL_psig_pend[signal]++;
1140 MUTEX_UNLOCK(&thread->mutex);
1142 /* Return the thread to allow for method chaining */
1144 /* XSRETURN(1); - implied */
1148 ithread_DESTROY(...)
1150 sv_unmagic(SvRV(ST(0)), PERL_MAGIC_shared_scalar);
1158 /* Compares TIDs to determine thread equality */
1159 if (sv_isobject(ST(0)) && sv_isobject(ST(1))) {
1160 ithread *thr1 = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1161 ithread *thr2 = INT2PTR(ithread *, SvIV(SvRV(ST(1))));
1162 are_equal = (thr1->tid == thr2->tid);
1167 /* Return 0 on false for backward compatibility */
1170 /* XSRETURN(1); - implied */
1181 /* Class method only */
1183 Perl_croak(aTHX_ "Usage: threads->object($tid)");
1184 classname = (char *)SvPV_nolen(ST(0));
1186 if ((items < 2) || ! SvOK(ST(1))) {
1190 /* threads->object($tid) */
1193 /* Walk through threads list */
1194 MUTEX_LOCK(&create_destruct_mutex);
1195 for (thread = threads->next;
1197 thread = thread->next)
1200 if (thread->tid == tid) {
1201 /* Ignore if detached or joined */
1202 if (! (thread->state & (PERL_ITHR_DETACHED|PERL_ITHR_JOINED))) {
1203 /* Put object on stack */
1204 ST(0) = sv_2mortal(ithread_to_SV(aTHX_ Nullsv, thread, classname, TRUE));
1210 MUTEX_UNLOCK(&create_destruct_mutex);
1215 /* XSRETURN(1); - implied */
1219 ithread__handle(...);
1223 thread = SV_to_ithread(aTHX_ ST(0));
1225 XST_mUV(0, PTR2UV(&thread->handle));
1227 XST_mUV(0, PTR2UV(&thread->thr));
1229 /* XSRETURN(1); - implied */
1233 ithread_get_stack_size(...)
1237 if (sv_isobject(ST(0))) {
1238 /* $thr->get_stack_size() */
1239 ithread *thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1240 stack_size = thread->stack_size;
1242 /* threads->get_stack_size() */
1243 stack_size = default_stack_size;
1245 XST_mIV(0, stack_size);
1246 /* XSRETURN(1); - implied */
1250 ithread_set_stack_size(...)
1255 Perl_croak(aTHX_ "Usage: threads->set_stack_size($size)");
1256 if (sv_isobject(ST(0)))
1257 Perl_croak(aTHX_ "Cannot change stack size of an existing thread");
1259 old_size = default_stack_size;
1260 default_stack_size = good_stack_size(aTHX_ SvIV(ST(1)));
1261 XST_mIV(0, old_size);
1262 /* XSRETURN(1); - implied */
1266 ithread_is_running(...)
1270 /* Object method only */
1271 if (! sv_isobject(ST(0)))
1272 Perl_croak(aTHX_ "Usage: $thr->is_running()");
1274 thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1275 ST(0) = (thread->state & PERL_ITHR_FINISHED) ? &PL_sv_no : &PL_sv_yes;
1276 /* XSRETURN(1); - implied */
1280 ithread_is_detached(...)
1284 thread = SV_to_ithread(aTHX_ ST(0));
1285 ST(0) = (thread->state & PERL_ITHR_DETACHED) ? &PL_sv_yes : &PL_sv_no;
1286 /* XSRETURN(1); - implied */
1290 ithread_is_joinable(...)
1294 /* Object method only */
1295 if (! sv_isobject(ST(0)))
1296 Perl_croak(aTHX_ "Usage: $thr->is_joinable()");
1298 thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1299 MUTEX_LOCK(&thread->mutex);
1300 ST(0) = ((thread->state & PERL_ITHR_FINISHED) &&
1301 ! (thread->state & (PERL_ITHR_DETACHED|PERL_ITHR_JOINED)))
1302 ? &PL_sv_yes : &PL_sv_no;
1303 MUTEX_UNLOCK(&thread->mutex);
1304 /* XSRETURN(1); - implied */
1308 ithread_wantarray(...)
1312 thread = SV_to_ithread(aTHX_ ST(0));
1313 ST(0) = (thread->gimme & G_ARRAY) ? &PL_sv_yes :
1314 (thread->gimme & G_VOID) ? &PL_sv_undef
1315 /* G_SCALAR */ : &PL_sv_no;
1316 /* XSRETURN(1); - implied */
1320 ithread_set_thread_exit_only(...)
1325 Perl_croak(aTHX_ "Usage: ->set_thread_exit_only(boolean)");
1326 thread = SV_to_ithread(aTHX_ ST(0));
1327 MUTEX_LOCK(&thread->mutex);
1328 if (SvTRUE(ST(1))) {
1329 thread->state |= PERL_ITHR_THREAD_EXIT_ONLY;
1331 thread->state &= ~PERL_ITHR_THREAD_EXIT_ONLY;
1333 MUTEX_UNLOCK(&thread->mutex);
1335 #endif /* USE_ITHREADS */
1341 /* The 'main' thread is thread 0.
1342 * It is detached (unjoinable) and immortal.
1348 PL_perl_destruct_level = 2;
1349 MUTEX_INIT(&create_destruct_mutex);
1350 MUTEX_LOCK(&create_destruct_mutex);
1352 PL_threadhook = &Perl_ithread_hook;
1354 thread = (ithread *)PerlMemShared_malloc(sizeof(ithread));
1356 PerlLIO_write(PerlIO_fileno(Perl_error_log), PL_no_mem, strlen(PL_no_mem));
1359 Zero(thread, 1, ithread);
1361 MUTEX_INIT(&thread->mutex);
1363 thread->tid = tid_counter++; /* Thread 0 */
1365 /* Head of the threads list */
1367 thread->next = thread;
1368 thread->prev = thread;
1370 thread->count = 1; /* Immortal */
1372 thread->interp = aTHX;
1373 thread->state = PERL_ITHR_DETACHED; /* Detached */
1374 thread->stack_size = default_stack_size;
1376 thread->thr = GetCurrentThreadId();
1378 thread->thr = pthread_self();
1381 S_ithread_set(aTHX_ thread);
1382 MUTEX_UNLOCK(&create_destruct_mutex);
1383 #endif /* USE_ITHREADS */