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 #define MY_CXT_KEY "threads::_guts" XS_VERSION
78 /* Used by Perl interpreter for thread context switching */
84 /* Structure for 'main' thread
85 * Also forms the 'base' for the doubly-linked list of threads */
86 STATIC ithread main_thread;
88 /* Protects the creation and destruction of threads*/
89 STATIC perl_mutex create_destruct_mutex;
91 STATIC UV tid_counter = 1;
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.context = thread;
115 return (MY_CXT.context);
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 /* Return if thread is still being used */
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);
190 /* Call PerlMemShared_free() in the context of the "first" interpreter
191 * per http://www.nntp.perl.org/group/perl.perl5.porters/110772
194 PerlMemShared_free(thread);
198 /* Warn if exiting with any unjoined threads */
204 MUTEX_LOCK(&create_destruct_mutex);
205 veto_cleanup = (running_threads || joinable_threads);
206 MUTEX_UNLOCK(&create_destruct_mutex);
209 if (ckWARN_d(WARN_THREADS)) {
210 Perl_warn(aTHX_ "Perl exited with active threads:\n\t%"
211 IVdf " running and unjoined\n\t%"
212 IVdf " finished and unjoined\n\t%"
213 IVdf " running and detached\n",
220 return (veto_cleanup);
223 /* Called on exit from main thread */
225 Perl_ithread_hook(pTHX)
227 return ((aTHX == PL_curinterp) ? S_exit_warning(aTHX) : 0);
231 /* MAGIC (in mg.h sense) hooks */
234 ithread_mg_get(pTHX_ SV *sv, MAGIC *mg)
236 ithread *thread = (ithread *)mg->mg_ptr;
237 SvIV_set(sv, PTR2IV(thread));
243 ithread_mg_free(pTHX_ SV *sv, MAGIC *mg)
245 ithread *thread = (ithread *)mg->mg_ptr;
248 MUTEX_LOCK(&thread->mutex);
249 cleanup = ((--thread->count == 0) &&
250 (thread->state & PERL_ITHR_FINISHED) &&
251 (thread->state & (PERL_ITHR_DETACHED|PERL_ITHR_JOINED)));
252 MUTEX_UNLOCK(&thread->mutex);
255 S_ithread_destruct(aTHX_ thread);
261 ithread_mg_dup(pTHX_ MAGIC *mg, CLONE_PARAMS *param)
263 ithread *thread = (ithread *)mg->mg_ptr;
264 MUTEX_LOCK(&thread->mutex);
266 MUTEX_UNLOCK(&thread->mutex);
270 MGVTBL ithread_vtbl = {
271 ithread_mg_get, /* get */
275 ithread_mg_free, /* free */
277 ithread_mg_dup /* dup */
281 /* Provided default, minimum and rational stack sizes */
283 S_good_stack_size(pTHX_ IV stack_size)
285 /* Use default stack size if no stack size specified */
287 return (default_stack_size);
290 #ifdef PTHREAD_STACK_MIN
291 /* Can't use less than minimum */
292 if (stack_size < PTHREAD_STACK_MIN) {
293 if (ckWARN(WARN_THREADS)) {
294 Perl_warn(aTHX_ "Using minimum thread stack size of %" IVdf, (IV)PTHREAD_STACK_MIN);
296 return (PTHREAD_STACK_MIN);
300 /* Round up to page size boundary */
301 if (page_size <= 0) {
302 #if defined(HAS_SYSCONF) && (defined(_SC_PAGESIZE) || defined(_SC_MMAP_PAGE_SIZE))
303 SETERRNO(0, SS_NORMAL);
305 page_size = sysconf(_SC_PAGESIZE);
307 page_size = sysconf(_SC_MMAP_PAGE_SIZE);
309 if ((long)page_size < 0) {
311 SV * const error = get_sv("@", FALSE);
312 (void)SvUPGRADE(error, SVt_PV);
313 Perl_croak(aTHX_ "PANIC: sysconf: %s", SvPV_nolen(error));
315 Perl_croak(aTHX_ "PANIC: sysconf: pagesize unknown");
319 # ifdef HAS_GETPAGESIZE
320 page_size = getpagesize();
322 # if defined(I_SYS_PARAM) && defined(PAGESIZE)
323 page_size = PAGESIZE;
325 page_size = 8192; /* A conservative default */
328 if (page_size <= 0) {
329 Perl_croak(aTHX_ "PANIC: bad pagesize %" IVdf, (IV)page_size);
333 stack_size = ((stack_size + (page_size - 1)) / page_size) * page_size;
339 /* Starts executing the thread.
340 * Passed as the C level function to run in the new thread.
343 STATIC THREAD_RET_TYPE
344 S_ithread_run(LPVOID arg)
347 S_ithread_run(void * arg)
350 ithread *thread = (ithread *)arg;
359 dTHXa(thread->interp);
361 /* Blocked until ->create() call finishes */
362 MUTEX_LOCK(&thread->mutex);
363 MUTEX_UNLOCK(&thread->mutex);
365 PERL_SET_CONTEXT(thread->interp);
366 S_ithread_set(aTHX_ thread);
368 PL_perl_destruct_level = 2;
371 AV *params = (AV *)SvRV(thread->params);
372 int len = (int)av_len(params)+1;
379 /* Put args on the stack */
381 for (ii=0; ii < len; ii++) {
382 XPUSHs(av_shift(params));
386 oldscope = PL_scopestack_ix;
389 /* Run the specified function */
390 len = (int)call_sv(thread->init_function, thread->gimme|G_EVAL);
391 } else if (jmp_rc == 2) {
394 exit_code = STATUS_CURRENT;
395 while (PL_scopestack_ix > oldscope) {
401 /* Remove args from stack and put back in params array */
403 for (ii=len-1; ii >= 0; ii--) {
406 av_store(params, ii, SvREFCNT_inc(sv));
413 /* Check for failure */
414 if (SvTRUE(ERRSV) && ckWARN_d(WARN_THREADS)) {
415 oldscope = PL_scopestack_ix;
418 /* Warn that thread died */
419 Perl_warn(aTHX_ "Thread %" UVuf " terminated abnormally: %" SVf, thread->tid, ERRSV);
420 } else if (jmp_rc == 2) {
421 /* Warn handler exited */
423 exit_code = STATUS_CURRENT;
424 while (PL_scopestack_ix > oldscope) {
431 /* Release function ref */
432 SvREFCNT_dec(thread->init_function);
433 thread->init_function = Nullsv;
436 PerlIO_flush((PerlIO *)NULL);
438 MUTEX_LOCK(&create_destruct_mutex);
439 MUTEX_LOCK(&thread->mutex);
440 /* Mark as finished */
441 thread->state |= PERL_ITHR_FINISHED;
442 /* Clear exit flag if required */
443 if (thread->state & PERL_ITHR_THREAD_EXIT_ONLY) {
446 /* Cleanup if detached */
447 cleanup = (thread->state & PERL_ITHR_DETACHED);
448 MUTEX_UNLOCK(&thread->mutex);
450 /* Adjust thread status counts */
457 MUTEX_UNLOCK(&create_destruct_mutex);
459 /* Exit application if required */
461 oldscope = PL_scopestack_ix;
464 /* Warn if there are unjoined threads */
465 S_exit_warning(aTHX);
466 } else if (jmp_rc == 2) {
467 /* Warn handler exited */
468 exit_code = STATUS_CURRENT;
469 while (PL_scopestack_ix > oldscope) {
478 /* Clean up detached thread */
480 S_ithread_destruct(aTHX_ thread);
491 /* Type conversion helper functions */
494 S_ithread_to_SV(pTHX_ SV *obj, ithread *thread, char *classname, bool inc)
499 /* If incrementing thread ref count, then call within mutex lock */
501 MUTEX_LOCK(&thread->mutex);
503 MUTEX_UNLOCK(&thread->mutex);
510 sv = newSVrv(obj, classname);
511 sv_setiv(sv, PTR2IV(thread));
512 mg = sv_magicext(sv, Nullsv, PERL_MAGIC_shared_scalar, &ithread_vtbl, (char *)thread, 0);
513 mg->mg_flags |= MGf_DUP;
520 S_SV_to_ithread(pTHX_ SV *sv)
522 /* Argument is a thread */
524 return (INT2PTR(ithread *, SvIV(SvRV(sv))));
526 /* Argument is classname, therefore return current thread */
527 return (S_ithread_get(aTHX));
532 * Called in context of parent thread.
533 * Called with create_destruct_mutex locked. (Unlocked on error.)
537 pTHX_ SV *init_function,
544 CLONE_PARAMS clone_param;
545 ithread *current_thread = S_ithread_get(aTHX);
547 SV **tmps_tmp = PL_tmps_stack;
548 IV tmps_ix = PL_tmps_ix;
550 int rc_stack_size = 0;
551 int rc_thread_create = 0;
554 /* Allocate thread structure */
555 thread = (ithread *)PerlMemShared_malloc(sizeof(ithread));
557 MUTEX_UNLOCK(&create_destruct_mutex);
558 PerlLIO_write(PerlIO_fileno(Perl_error_log), PL_no_mem, strlen(PL_no_mem));
561 Zero(thread, 1, ithread);
563 /* Add to threads list */
564 thread->next = &main_thread;
565 thread->prev = main_thread.prev;
566 main_thread.prev = thread;
567 thread->prev->next = thread;
569 /* Set count to 1 immediately in case thread exits before
570 * we return to caller!
574 /* Block new thread until ->create() call finishes */
575 MUTEX_INIT(&thread->mutex);
576 MUTEX_LOCK(&thread->mutex);
578 thread->tid = tid_counter++;
579 thread->stack_size = S_good_stack_size(aTHX_ stack_size);
580 thread->gimme = gimme;
581 thread->state = exit_opt;
583 /* "Clone" our interpreter into the thread's interpreter.
584 * This gives thread access to "static data" and code.
586 PerlIO_flush((PerlIO *)NULL);
587 S_ithread_set(aTHX_ thread);
589 SAVEBOOL(PL_srand_called); /* Save this so it becomes the correct value */
590 PL_srand_called = FALSE; /* Set it to false so we can detect if it gets
591 set during the clone */
594 thread->interp = perl_clone(aTHX, CLONEf_KEEP_PTR_TABLE | CLONEf_CLONE_HOST);
596 thread->interp = perl_clone(aTHX, CLONEf_KEEP_PTR_TABLE);
599 /* perl_clone() leaves us in new interpreter's context. As it is tricky
600 * to spot an implicit aTHX, create a new scope with aTHX matching the
601 * context for the duration of our work for new interpreter.
604 dTHXa(thread->interp);
608 /* Here we remove END blocks since they should only run in the thread
611 SvREFCNT_dec(PL_endav);
614 if (SvPOK(init_function)) {
615 thread->init_function = newSV(0);
616 sv_copypv(thread->init_function, init_function);
618 clone_param.flags = 0;
619 thread->init_function = sv_dup(init_function, &clone_param);
620 if (SvREFCNT(thread->init_function) == 0) {
621 SvREFCNT_inc_void(thread->init_function);
625 thread->params = sv_dup(params, &clone_param);
626 SvREFCNT_inc_void(thread->params);
628 /* The code below checks that anything living on the tmps stack and
629 * has been cloned (so it lives in the ptr_table) has a refcount
632 * If the refcount is 0 it means that a something on the stack/context
633 * was holding a reference to it and since we init_stacks() in
634 * perl_clone that won't get cleaned and we will get a leaked scalar.
635 * The reason it was cloned was that it lived on the @_ stack.
637 * Example of this can be found in bugreport 15837 where calls in the
638 * parameter list end up as a temp.
640 * One could argue that this fix should be in perl_clone.
642 while (tmps_ix > 0) {
643 SV* sv = (SV*)ptr_table_fetch(PL_ptr_table, tmps_tmp[tmps_ix]);
645 if (sv && SvREFCNT(sv) == 0) {
646 SvREFCNT_inc_void(sv);
651 SvTEMP_off(thread->init_function);
652 ptr_table_free(PL_ptr_table);
654 PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
656 S_ithread_set(aTHX_ current_thread);
657 PERL_SET_CONTEXT(aTHX);
659 /* Create/start the thread */
661 thread->handle = CreateThread(NULL,
662 (DWORD)thread->stack_size,
665 STACK_SIZE_PARAM_IS_A_RESERVATION,
669 STATIC pthread_attr_t attr;
670 STATIC int attr_inited = 0;
671 STATIC int attr_joinable = PTHREAD_CREATE_JOINABLE;
673 pthread_attr_init(&attr);
677 # ifdef PTHREAD_ATTR_SETDETACHSTATE
678 /* Threads start out joinable */
679 PTHREAD_ATTR_SETDETACHSTATE(&attr, attr_joinable);
682 # ifdef _POSIX_THREAD_ATTR_STACKSIZE
683 /* Set thread's stack size */
684 if (thread->stack_size > 0) {
685 rc_stack_size = pthread_attr_setstacksize(&attr, (size_t)thread->stack_size);
689 /* Create the thread */
690 if (! rc_stack_size) {
691 # ifdef OLD_PTHREADS_API
692 rc_thread_create = pthread_create(&thread->thr,
697 # if defined(HAS_PTHREAD_ATTR_SETSCOPE) && defined(PTHREAD_SCOPE_SYSTEM)
698 pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);
700 rc_thread_create = pthread_create(&thread->thr,
707 # ifdef _POSIX_THREAD_ATTR_STACKSIZE
708 /* Try to get thread's actual stack size */
712 stacksize = pthread_attr_getstacksize(attr);
714 if (! pthread_attr_getstacksize(&attr, &stacksize))
717 thread->stack_size = (IV)stacksize;
724 /* Check for errors */
726 if (thread->handle == NULL) {
728 if (rc_stack_size || rc_thread_create) {
730 /* Must unlock mutex for destruct call */
731 MUTEX_UNLOCK(&create_destruct_mutex);
733 S_ithread_destruct(aTHX_ thread);
735 if (ckWARN_d(WARN_THREADS)) {
737 Perl_warn(aTHX_ "Thread creation failed: pthread_attr_setstacksize(%" IVdf ") returned %d", thread->stack_size, rc_stack_size);
739 Perl_warn(aTHX_ "Thread creation failed: pthread_create returned %d", rc_thread_create);
751 #endif /* USE_ITHREADS */
754 MODULE = threads PACKAGE = threads PREFIX = ithread_
764 SV *function_to_call;
770 SV *thread_exit_only;
775 if ((items >= 2) && SvROK(ST(1)) && SvTYPE(SvRV(ST(1)))==SVt_PVHV) {
777 Perl_croak(aTHX_ "Usage: threads->create(\\%specs, function, ...)");
779 specs = (HV*)SvRV(ST(1));
783 Perl_croak(aTHX_ "Usage: threads->create(function, ...)");
789 if (sv_isobject(ST(0))) {
791 classname = HvNAME(SvSTASH(SvRV(ST(0))));
792 thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
793 stack_size = thread->stack_size;
794 exit_opt = thread->state & PERL_ITHR_THREAD_EXIT_ONLY;
796 /* threads->create() */
797 classname = (char *)SvPV_nolen(ST(0));
798 stack_size = default_stack_size;
799 thread_exit_only = get_sv("threads::thread_exit_only", TRUE);
800 exit_opt = (SvTRUE(thread_exit_only))
801 ? PERL_ITHR_THREAD_EXIT_ONLY : 0;
804 function_to_call = ST(idx+1);
809 if (hv_exists(specs, "stack", 5)) {
810 stack_size = SvIV(*hv_fetch(specs, "stack", 5, 0));
811 } else if (hv_exists(specs, "stacksize", 9)) {
812 stack_size = SvIV(*hv_fetch(specs, "stacksize", 9, 0));
813 } else if (hv_exists(specs, "stack_size", 10)) {
814 stack_size = SvIV(*hv_fetch(specs, "stack_size", 10, 0));
818 if (hv_exists(specs, "context", 7)) {
819 str = (char *)SvPV_nolen(*hv_fetch(specs, "context", 7, 0));
834 Perl_croak(aTHX_ "Invalid context: %s", str);
836 } else if (hv_exists(specs, "array", 5)) {
837 if (SvTRUE(*hv_fetch(specs, "array", 5, 0))) {
840 } else if (hv_exists(specs, "scalar", 6)) {
841 if (SvTRUE(*hv_fetch(specs, "scalar", 6, 0))) {
844 } else if (hv_exists(specs, "void", 4)) {
845 if (SvTRUE(*hv_fetch(specs, "void", 4, 0))) {
850 /* exit => thread_only */
851 if (hv_exists(specs, "exit", 4)) {
852 str = (char *)SvPV_nolen(*hv_fetch(specs, "exit", 4, 0));
853 exit_opt = (*str == 't' || *str == 'T')
854 ? PERL_ITHR_THREAD_EXIT_ONLY : 0;
858 context = GIMME_V; /* Implicit context */
860 context |= (GIMME_V & (~(G_ARRAY|G_SCALAR|G_VOID)));
866 for (ii=2; ii < items ; ii++) {
867 av_push(params, SvREFCNT_inc(ST(idx+ii)));
872 MUTEX_LOCK(&create_destruct_mutex);
873 thread = S_ithread_create(aTHX_ function_to_call,
877 newRV_noinc((SV*)params));
879 XSRETURN_UNDEF; /* Mutex already unlocked */
881 ST(0) = sv_2mortal(S_ithread_to_SV(aTHX_ Nullsv, thread, classname, FALSE));
884 MUTEX_UNLOCK(&thread->mutex);
885 MUTEX_UNLOCK(&create_destruct_mutex);
887 /* XSRETURN(1); - implied */
899 /* Class method only */
901 Perl_croak(aTHX_ "Usage: threads->list(...)");
903 classname = (char *)SvPV_nolen(ST(0));
905 /* Calling context */
906 list_context = (GIMME_V == G_ARRAY);
908 /* Running or joinable parameter */
910 want_running = SvTRUE(ST(1));
913 /* Walk through threads list */
914 MUTEX_LOCK(&create_destruct_mutex);
915 for (thread = main_thread.next;
916 thread != &main_thread;
917 thread = thread->next)
919 /* Ignore detached or joined threads */
920 if (thread->state & (PERL_ITHR_DETACHED|PERL_ITHR_JOINED)) {
924 /* Filter per parameter */
927 if (thread->state & PERL_ITHR_FINISHED) {
928 continue; /* Not running */
931 if (! (thread->state & PERL_ITHR_FINISHED)) {
932 continue; /* Still running - not joinable yet */
937 /* Push object on stack if list context */
939 XPUSHs(sv_2mortal(S_ithread_to_SV(aTHX_ Nullsv, thread, classname, TRUE)));
943 MUTEX_UNLOCK(&create_destruct_mutex);
944 /* If scalar context, send back count */
945 if (! list_context) {
956 /* Class method only */
958 Perl_croak(aTHX_ "Usage: threads->self()");
960 classname = (char *)SvPV_nolen(ST(0));
962 thread = S_ithread_get(aTHX);
964 ST(0) = sv_2mortal(S_ithread_to_SV(aTHX_ Nullsv, thread, classname, TRUE));
965 /* XSRETURN(1); - implied */
973 thread = S_SV_to_ithread(aTHX_ ST(0));
974 XST_mUV(0, thread->tid);
975 /* XSRETURN(1); - implied */
992 /* Object method only */
993 if (! sv_isobject(ST(0))) {
994 Perl_croak(aTHX_ "Usage: $thr->join()");
997 /* Check if the thread is joinable */
998 thread = S_SV_to_ithread(aTHX_ ST(0));
999 join_err = (thread->state & (PERL_ITHR_DETACHED|PERL_ITHR_JOINED));
1001 if (join_err & PERL_ITHR_DETACHED) {
1002 Perl_croak(aTHX_ "Cannot join a detached thread");
1004 Perl_croak(aTHX_ "Thread already joined");
1008 /* Join the thread */
1010 waitcode = WaitForSingleObject(thread->handle, INFINITE);
1012 pthread_join(thread->thr, &retval);
1015 MUTEX_LOCK(&thread->mutex);
1016 /* Mark as joined */
1017 thread->state |= PERL_ITHR_JOINED;
1019 /* Get the return value from the call_sv */
1022 PerlInterpreter *other_perl;
1023 CLONE_PARAMS clone_params;
1024 ithread *current_thread;
1026 params_copy = (AV *)SvRV(thread->params);
1027 other_perl = thread->interp;
1028 clone_params.stashes = newAV();
1029 clone_params.flags = CLONEf_JOIN_IN;
1030 PL_ptr_table = ptr_table_new();
1031 current_thread = S_ithread_get(aTHX);
1032 S_ithread_set(aTHX_ thread);
1033 /* Ensure 'meaningful' addresses retain their meaning */
1034 ptr_table_store(PL_ptr_table, &other_perl->Isv_undef, &PL_sv_undef);
1035 ptr_table_store(PL_ptr_table, &other_perl->Isv_no, &PL_sv_no);
1036 ptr_table_store(PL_ptr_table, &other_perl->Isv_yes, &PL_sv_yes);
1037 params = (AV *)sv_dup((SV*)params_copy, &clone_params);
1038 S_ithread_set(aTHX_ current_thread);
1039 SvREFCNT_dec(clone_params.stashes);
1040 SvREFCNT_inc_void(params);
1041 ptr_table_free(PL_ptr_table);
1042 PL_ptr_table = NULL;
1045 /* We are finished with the thread */
1046 S_ithread_clear(aTHX_ thread);
1047 MUTEX_UNLOCK(&thread->mutex);
1049 MUTEX_LOCK(&create_destruct_mutex);
1050 if (! (thread->state & PERL_ITHR_DETACHED)) {
1053 MUTEX_UNLOCK(&create_destruct_mutex);
1055 /* If no return values, then just return */
1060 /* Put return values on stack */
1061 len = (int)AvFILL(params);
1062 for (ii=0; ii <= len; ii++) {
1063 SV* param = av_shift(params);
1064 XPUSHs(sv_2mortal(param));
1067 /* Free return value array */
1068 SvREFCNT_dec(params);
1084 /* Check if the thread is detachable */
1085 thread = S_SV_to_ithread(aTHX_ ST(0));
1086 if ((detach_err = (thread->state & (PERL_ITHR_DETACHED|PERL_ITHR_JOINED)))) {
1087 if (detach_err & PERL_ITHR_DETACHED) {
1088 Perl_croak(aTHX_ "Thread already detached");
1090 Perl_croak(aTHX_ "Cannot detach a joined thread");
1094 /* Detach the thread */
1095 MUTEX_LOCK(&create_destruct_mutex);
1096 MUTEX_LOCK(&thread->mutex);
1097 thread->state |= PERL_ITHR_DETACHED;
1099 /* Windows has no 'detach thread' function */
1101 PERL_THREAD_DETACH(thread->thr);
1103 /* Cleanup if finished */
1104 cleanup = (thread->state & PERL_ITHR_FINISHED);
1105 MUTEX_UNLOCK(&thread->mutex);
1113 MUTEX_UNLOCK(&create_destruct_mutex);
1116 S_ithread_destruct(aTHX_ thread);
1127 /* Must have safe signals */
1128 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG) {
1129 Perl_croak(aTHX_ "Cannot signal threads without safe signals");
1132 /* Object method only */
1133 if (! sv_isobject(ST(0))) {
1134 Perl_croak(aTHX_ "Usage: $thr->kill('SIG...')");
1138 sig_name = SvPV_nolen(ST(1));
1139 if (isALPHA(*sig_name)) {
1140 if (*sig_name == 'S' && sig_name[1] == 'I' && sig_name[2] == 'G') {
1143 if ((signal = whichsig(sig_name)) < 0) {
1144 Perl_croak(aTHX_ "Unrecognized signal name: %s", sig_name);
1147 signal = SvIV(ST(1));
1150 /* Set the signal for the thread */
1151 thread = S_SV_to_ithread(aTHX_ ST(0));
1152 MUTEX_LOCK(&thread->mutex);
1153 if (thread->interp) {
1154 dTHXa(thread->interp);
1155 PL_psig_pend[signal]++;
1158 MUTEX_UNLOCK(&thread->mutex);
1160 /* Return the thread to allow for method chaining */
1162 /* XSRETURN(1); - implied */
1166 ithread_DESTROY(...)
1168 sv_unmagic(SvRV(ST(0)), PERL_MAGIC_shared_scalar);
1176 /* Compares TIDs to determine thread equality */
1177 if (sv_isobject(ST(0)) && sv_isobject(ST(1))) {
1178 ithread *thr1 = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1179 ithread *thr2 = INT2PTR(ithread *, SvIV(SvRV(ST(1))));
1180 are_equal = (thr1->tid == thr2->tid);
1185 /* Return 0 on false for backward compatibility */
1188 /* XSRETURN(1); - implied */
1199 /* Class method only */
1201 Perl_croak(aTHX_ "Usage: threads->object($tid)");
1203 classname = (char *)SvPV_nolen(ST(0));
1205 if ((items < 2) || ! SvOK(ST(1))) {
1209 /* threads->object($tid) */
1212 /* Walk through threads list */
1213 MUTEX_LOCK(&create_destruct_mutex);
1214 for (thread = main_thread.next;
1215 thread != &main_thread;
1216 thread = thread->next)
1219 if (thread->tid == tid) {
1220 /* Ignore if detached or joined */
1221 if (! (thread->state & (PERL_ITHR_DETACHED|PERL_ITHR_JOINED))) {
1222 /* Put object on stack */
1223 ST(0) = sv_2mortal(S_ithread_to_SV(aTHX_ Nullsv, thread, classname, TRUE));
1229 MUTEX_UNLOCK(&create_destruct_mutex);
1234 /* XSRETURN(1); - implied */
1238 ithread__handle(...);
1242 thread = S_SV_to_ithread(aTHX_ ST(0));
1244 XST_mUV(0, PTR2UV(&thread->handle));
1246 XST_mUV(0, PTR2UV(&thread->thr));
1248 /* XSRETURN(1); - implied */
1252 ithread_get_stack_size(...)
1256 if (sv_isobject(ST(0))) {
1257 /* $thr->get_stack_size() */
1258 ithread *thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1259 stack_size = thread->stack_size;
1261 /* threads->get_stack_size() */
1262 stack_size = default_stack_size;
1264 XST_mIV(0, stack_size);
1265 /* XSRETURN(1); - implied */
1269 ithread_set_stack_size(...)
1274 Perl_croak(aTHX_ "Usage: threads->set_stack_size($size)");
1276 if (sv_isobject(ST(0))) {
1277 Perl_croak(aTHX_ "Cannot change stack size of an existing thread");
1280 old_size = default_stack_size;
1281 default_stack_size = S_good_stack_size(aTHX_ SvIV(ST(1)));
1282 XST_mIV(0, old_size);
1283 /* XSRETURN(1); - implied */
1287 ithread_is_running(...)
1291 /* Object method only */
1292 if (! sv_isobject(ST(0))) {
1293 Perl_croak(aTHX_ "Usage: $thr->is_running()");
1296 thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1297 ST(0) = (thread->state & PERL_ITHR_FINISHED) ? &PL_sv_no : &PL_sv_yes;
1298 /* XSRETURN(1); - implied */
1302 ithread_is_detached(...)
1306 thread = S_SV_to_ithread(aTHX_ ST(0));
1307 ST(0) = (thread->state & PERL_ITHR_DETACHED) ? &PL_sv_yes : &PL_sv_no;
1308 /* XSRETURN(1); - implied */
1312 ithread_is_joinable(...)
1316 /* Object method only */
1317 if (! sv_isobject(ST(0))) {
1318 Perl_croak(aTHX_ "Usage: $thr->is_joinable()");
1321 thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1322 MUTEX_LOCK(&thread->mutex);
1323 ST(0) = ((thread->state & PERL_ITHR_FINISHED) &&
1324 ! (thread->state & (PERL_ITHR_DETACHED|PERL_ITHR_JOINED)))
1325 ? &PL_sv_yes : &PL_sv_no;
1326 MUTEX_UNLOCK(&thread->mutex);
1327 /* XSRETURN(1); - implied */
1331 ithread_wantarray(...)
1335 thread = S_SV_to_ithread(aTHX_ ST(0));
1336 ST(0) = (thread->gimme & G_ARRAY) ? &PL_sv_yes :
1337 (thread->gimme & G_VOID) ? &PL_sv_undef
1338 /* G_SCALAR */ : &PL_sv_no;
1339 /* XSRETURN(1); - implied */
1343 ithread_set_thread_exit_only(...)
1348 Perl_croak(aTHX_ "Usage: ->set_thread_exit_only(boolean)");
1350 thread = S_SV_to_ithread(aTHX_ ST(0));
1351 MUTEX_LOCK(&thread->mutex);
1352 if (SvTRUE(ST(1))) {
1353 thread->state |= PERL_ITHR_THREAD_EXIT_ONLY;
1355 thread->state &= ~PERL_ITHR_THREAD_EXIT_ONLY;
1357 MUTEX_UNLOCK(&thread->mutex);
1359 #endif /* USE_ITHREADS */
1367 PL_perl_destruct_level = 2;
1368 MUTEX_INIT(&create_destruct_mutex);
1369 MUTEX_LOCK(&create_destruct_mutex);
1371 PL_threadhook = &Perl_ithread_hook;
1373 /* The 'main' thread is thread 0.
1374 * It is detached (unjoinable) and immortal.
1376 Zero(&main_thread, 1, ithread); /* Thread 0 */
1378 MUTEX_INIT(&main_thread.mutex);
1380 /* Head of the threads list */
1381 main_thread.next = &main_thread;
1382 main_thread.prev = &main_thread;
1384 main_thread.count = 1; /* Immortal */
1386 main_thread.interp = aTHX;
1387 main_thread.state = PERL_ITHR_DETACHED; /* Detached */
1388 main_thread.stack_size = default_stack_size;
1390 main_thread.thr = GetCurrentThreadId();
1392 main_thread.thr = pthread_self();
1395 S_ithread_set(aTHX_ &main_thread);
1396 MUTEX_UNLOCK(&create_destruct_mutex);
1397 #endif /* USE_ITHREADS */