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);
142 thread->interp = NULL;
147 PERL_SET_CONTEXT(aTHX);
151 /* Free an ithread structure and any attached data if its count == 0 */
153 S_ithread_destruct(pTHX_ ithread *thread)
159 MUTEX_LOCK(&thread->mutex);
161 /* Thread is still in use */
162 if (thread->count != 0) {
163 MUTEX_UNLOCK(&thread->mutex);
167 /* Main thread (0) is immortal and should never get here */
168 assert(thread->tid != 0);
170 /* Remove from circular list of threads */
171 MUTEX_LOCK(&create_destruct_mutex);
172 thread->next->prev = thread->prev;
173 thread->prev->next = thread->next;
176 MUTEX_UNLOCK(&create_destruct_mutex);
178 /* Thread is now disowned */
179 S_ithread_clear(aTHX_ thread);
182 handle = thread->handle;
183 thread->handle = NULL;
185 MUTEX_UNLOCK(&thread->mutex);
186 MUTEX_DESTROY(&thread->mutex);
193 /* Call PerlMemShared_free() in the context of the "first" interpreter
194 * per http://www.nntp.perl.org/group/perl.perl5.porters/110772
197 PerlMemShared_free(thread);
201 /* Warn if exiting with any unjoined threads */
207 MUTEX_LOCK(&create_destruct_mutex);
208 veto_cleanup = (running_threads || joinable_threads);
209 MUTEX_UNLOCK(&create_destruct_mutex);
212 if (ckWARN_d(WARN_THREADS)) {
213 Perl_warn(aTHX_ "Perl exited with active threads:\n\t%"
214 IVdf " running and unjoined\n\t%"
215 IVdf " finished and unjoined\n\t%"
216 IVdf " running and detached\n",
223 return (veto_cleanup);
226 /* Called on exit from main thread */
228 Perl_ithread_hook(pTHX)
230 return ((aTHX == PL_curinterp) ? S_exit_warning(aTHX) : 0);
234 /* MAGIC (in mg.h sense) hooks */
237 ithread_mg_get(pTHX_ SV *sv, MAGIC *mg)
239 ithread *thread = (ithread *)mg->mg_ptr;
240 SvIV_set(sv, PTR2IV(thread));
246 ithread_mg_free(pTHX_ SV *sv, MAGIC *mg)
248 ithread *thread = (ithread *)mg->mg_ptr;
251 MUTEX_LOCK(&thread->mutex);
252 cleanup = ((--thread->count == 0) &&
253 (thread->state & PERL_ITHR_FINISHED) &&
254 (thread->state & (PERL_ITHR_DETACHED|PERL_ITHR_JOINED)));
255 MUTEX_UNLOCK(&thread->mutex);
258 S_ithread_destruct(aTHX_ thread);
263 ithread_mg_dup(pTHX_ MAGIC *mg, CLONE_PARAMS *param)
265 ithread *thread = (ithread *)mg->mg_ptr;
266 MUTEX_LOCK(&thread->mutex);
268 MUTEX_UNLOCK(&thread->mutex);
272 MGVTBL ithread_vtbl = {
273 ithread_mg_get, /* get */
277 ithread_mg_free, /* free */
279 ithread_mg_dup /* dup */
283 /* Provided default, minimum and rational stack sizes */
285 good_stack_size(pTHX_ IV stack_size)
287 /* Use default stack size if no stack size specified */
289 return (default_stack_size);
291 #ifdef PTHREAD_STACK_MIN
292 /* Can't use less than minimum */
293 if (stack_size < PTHREAD_STACK_MIN) {
294 if (ckWARN(WARN_THREADS)) {
295 Perl_warn(aTHX_ "Using minimum thread stack size of %" IVdf, (IV)PTHREAD_STACK_MIN);
297 return (PTHREAD_STACK_MIN);
301 /* Round up to page size boundary */
302 if (page_size <= 0) {
303 #if defined(HAS_SYSCONF) && (defined(_SC_PAGESIZE) || defined(_SC_MMAP_PAGE_SIZE))
304 SETERRNO(0, SS_NORMAL);
306 page_size = sysconf(_SC_PAGESIZE);
308 page_size = sysconf(_SC_MMAP_PAGE_SIZE);
310 if ((long)page_size < 0) {
312 SV * const error = get_sv("@", FALSE);
313 (void)SvUPGRADE(error, SVt_PV);
314 Perl_croak(aTHX_ "PANIC: sysconf: %s", SvPV_nolen(error));
316 Perl_croak(aTHX_ "PANIC: sysconf: pagesize unknown");
320 # ifdef HAS_GETPAGESIZE
321 page_size = getpagesize();
323 # if defined(I_SYS_PARAM) && defined(PAGESIZE)
324 page_size = PAGESIZE;
326 page_size = 8192; /* A conservative default */
330 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);
360 PERL_SET_CONTEXT(thread->interp);
361 S_ithread_set(aTHX_ thread);
364 /* Far from clear messing with ->thr child-side is a good idea */
365 MUTEX_LOCK(&thread->mutex);
367 thread->thr = GetCurrentThreadId();
369 thread->thr = pthread_self();
371 MUTEX_UNLOCK(&thread->mutex);
374 PL_perl_destruct_level = 2;
377 AV *params = (AV *)SvRV(thread->params);
378 int len = (int)av_len(params)+1;
385 /* Put args on the stack */
387 for (ii=0; ii < len; ii++) {
388 XPUSHs(av_shift(params));
392 oldscope = PL_scopestack_ix;
395 /* Run the specified function */
396 len = (int)call_sv(thread->init_function, thread->gimme|G_EVAL);
397 } else if (jmp_rc == 2) {
400 exit_code = STATUS_CURRENT;
401 while (PL_scopestack_ix > oldscope) {
407 /* Remove args from stack and put back in params array */
409 for (ii=len-1; ii >= 0; ii--) {
412 av_store(params, ii, SvREFCNT_inc(sv));
419 /* Check for failure */
420 if (SvTRUE(ERRSV) && ckWARN_d(WARN_THREADS)) {
421 oldscope = PL_scopestack_ix;
424 /* Warn that thread died */
425 Perl_warn(aTHX_ "Thread %" UVuf " terminated abnormally: %" SVf, thread->tid, ERRSV);
426 } else if (jmp_rc == 2) {
427 /* Warn handler exited */
429 exit_code = STATUS_CURRENT;
430 while (PL_scopestack_ix > oldscope) {
437 /* Release function ref */
438 SvREFCNT_dec(thread->init_function);
439 thread->init_function = Nullsv;
442 PerlIO_flush((PerlIO *)NULL);
444 MUTEX_LOCK(&thread->mutex);
445 /* Mark as finished */
446 thread->state |= PERL_ITHR_FINISHED;
447 /* Clear exit flag if required */
448 if (thread->state & PERL_ITHR_THREAD_EXIT_ONLY)
450 /* Cleanup if detached */
451 cleanup = (thread->state & PERL_ITHR_DETACHED);
452 MUTEX_UNLOCK(&thread->mutex);
454 /* Adjust thread status counts */
455 MUTEX_LOCK(&create_destruct_mutex);
462 MUTEX_UNLOCK(&create_destruct_mutex);
464 /* Exit application if required */
466 oldscope = PL_scopestack_ix;
469 /* Warn if there are unjoined threads */
470 S_exit_warning(aTHX);
471 } else if (jmp_rc == 2) {
472 /* Warn handler exited */
473 exit_code = STATUS_CURRENT;
474 while (PL_scopestack_ix > oldscope) {
483 /* Clean up detached thread */
485 S_ithread_destruct(aTHX_ thread);
495 /* Type conversion helper functions */
497 ithread_to_SV(pTHX_ SV *obj, ithread *thread, char *classname, bool inc)
503 MUTEX_LOCK(&thread->mutex);
505 MUTEX_UNLOCK(&thread->mutex);
512 sv = newSVrv(obj, classname);
513 sv_setiv(sv, PTR2IV(thread));
514 mg = sv_magicext(sv, Nullsv, PERL_MAGIC_shared_scalar, &ithread_vtbl, (char *)thread, 0);
515 mg->mg_flags |= MGf_DUP;
522 SV_to_ithread(pTHX_ SV *sv)
524 /* Argument is a thread */
526 return (INT2PTR(ithread *, SvIV(SvRV(sv))));
528 /* Argument is classname, therefore return current thread */
529 return (S_ithread_get(aTHX));
534 * Called in context of parent thread.
547 CLONE_PARAMS clone_param;
548 ithread *current_thread = S_ithread_get(aTHX);
550 SV **tmps_tmp = PL_tmps_stack;
551 IV tmps_ix = PL_tmps_ix;
553 int rc_stack_size = 0;
554 int rc_thread_create = 0;
557 MUTEX_LOCK(&create_destruct_mutex);
559 /* Allocate thread structure */
560 thread = (ithread *)PerlMemShared_malloc(sizeof(ithread));
562 MUTEX_UNLOCK(&create_destruct_mutex);
563 PerlLIO_write(PerlIO_fileno(Perl_error_log), PL_no_mem, strlen(PL_no_mem));
566 Zero(thread, 1, ithread);
568 /* Add to threads list */
569 thread->next = threads;
570 thread->prev = threads->prev;
571 threads->prev = thread;
572 thread->prev->next = thread;
574 /* Set count to 1 immediately in case thread exits before
575 * we return to caller!
579 MUTEX_INIT(&thread->mutex);
580 thread->tid = tid_counter++;
581 thread->stack_size = good_stack_size(aTHX_ stack_size);
582 thread->gimme = gimme;
583 thread->state = exit_opt;
585 /* "Clone" our interpreter into the thread's interpreter.
586 * This gives thread access to "static data" and code.
588 PerlIO_flush((PerlIO *)NULL);
589 S_ithread_set(aTHX_ thread);
591 SAVEBOOL(PL_srand_called); /* Save this so it becomes the correct value */
592 PL_srand_called = FALSE; /* Set it to false so we can detect if it gets
593 set during the clone */
596 thread->interp = perl_clone(aTHX, CLONEf_KEEP_PTR_TABLE | CLONEf_CLONE_HOST);
598 thread->interp = perl_clone(aTHX, CLONEf_KEEP_PTR_TABLE);
601 /* perl_clone() leaves us in new interpreter's context. As it is tricky
602 * to spot an implicit aTHX, create a new scope with aTHX matching the
603 * context for the duration of our work for new interpreter.
606 dTHXa(thread->interp);
610 /* Here we remove END blocks since they should only run in the thread
613 SvREFCNT_dec(PL_endav);
616 if (SvPOK(init_function)) {
617 thread->init_function = newSV(0);
618 sv_copypv(thread->init_function, init_function);
620 clone_param.flags = 0;
621 thread->init_function = sv_dup(init_function, &clone_param);
622 if (SvREFCNT(thread->init_function) == 0) {
623 SvREFCNT_inc(thread->init_function);
627 thread->params = sv_dup(params, &clone_param);
628 SvREFCNT_inc(thread->params);
630 /* The code below checks that anything living on the tmps stack and
631 * has been cloned (so it lives in the ptr_table) has a refcount
634 * If the refcount is 0 it means that a something on the stack/context
635 * was holding a reference to it and since we init_stacks() in
636 * perl_clone that won't get cleaned and we will get a leaked scalar.
637 * The reason it was cloned was that it lived on the @_ stack.
639 * Example of this can be found in bugreport 15837 where calls in the
640 * parameter list end up as a temp.
642 * One could argue that this fix should be in perl_clone.
644 while (tmps_ix > 0) {
645 SV* sv = (SV*)ptr_table_fetch(PL_ptr_table, tmps_tmp[tmps_ix]);
647 if (sv && SvREFCNT(sv) == 0) {
653 SvTEMP_off(thread->init_function);
654 ptr_table_free(PL_ptr_table);
656 PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
658 S_ithread_set(aTHX_ current_thread);
659 PERL_SET_CONTEXT(aTHX);
661 /* Create/start the thread */
663 thread->handle = CreateThread(NULL,
664 (DWORD)thread->stack_size,
667 STACK_SIZE_PARAM_IS_A_RESERVATION,
671 static pthread_attr_t attr;
672 static int attr_inited = 0;
673 static int attr_joinable = PTHREAD_CREATE_JOINABLE;
675 pthread_attr_init(&attr);
679 # ifdef PTHREAD_ATTR_SETDETACHSTATE
680 /* Threads start out joinable */
681 PTHREAD_ATTR_SETDETACHSTATE(&attr, attr_joinable);
684 # ifdef _POSIX_THREAD_ATTR_STACKSIZE
685 /* Set thread's stack size */
686 if (thread->stack_size > 0) {
687 rc_stack_size = pthread_attr_setstacksize(&attr, (size_t)thread->stack_size);
691 /* Create the thread */
692 if (! rc_stack_size) {
693 # ifdef OLD_PTHREADS_API
694 rc_thread_create = pthread_create(&thread->thr,
699 # if defined(HAS_PTHREAD_ATTR_SETSCOPE) && defined(PTHREAD_SCOPE_SYSTEM)
700 pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);
702 rc_thread_create = pthread_create(&thread->thr,
709 # ifdef _POSIX_THREAD_ATTR_STACKSIZE
710 /* Try to get thread's actual stack size */
714 stacksize = pthread_attr_getstacksize(attr);
716 if (! pthread_attr_getstacksize(&attr, &stacksize))
719 thread->stack_size = (IV)stacksize;
726 /* Check for errors */
728 if (thread->handle == NULL) {
730 if (rc_stack_size || rc_thread_create) {
732 MUTEX_UNLOCK(&create_destruct_mutex);
734 S_ithread_destruct(aTHX_ thread);
736 if (ckWARN_d(WARN_THREADS)) {
738 Perl_warn(aTHX_ "Thread creation failed: pthread_attr_setstacksize(%" IVdf ") returned %d", thread->stack_size, rc_stack_size);
740 Perl_warn(aTHX_ "Thread creation failed: pthread_create returned %d", rc_thread_create);
743 return (&PL_sv_undef);
747 MUTEX_UNLOCK(&create_destruct_mutex);
751 return (ithread_to_SV(aTHX_ obj, thread, classname, FALSE));
754 #endif /* USE_ITHREADS */
757 MODULE = threads PACKAGE = threads PREFIX = ithread_
767 SV *function_to_call;
773 SV *thread_exit_only;
778 if ((items >= 2) && SvROK(ST(1)) && SvTYPE(SvRV(ST(1)))==SVt_PVHV) {
780 Perl_croak(aTHX_ "Usage: threads->create(\\%specs, function, ...)");
781 specs = (HV*)SvRV(ST(1));
785 Perl_croak(aTHX_ "Usage: threads->create(function, ...)");
790 if (sv_isobject(ST(0))) {
792 classname = HvNAME(SvSTASH(SvRV(ST(0))));
793 thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
794 stack_size = thread->stack_size;
795 exit_opt = thread->state & PERL_ITHR_THREAD_EXIT_ONLY;
797 /* threads->create() */
798 classname = (char *)SvPV_nolen(ST(0));
799 stack_size = default_stack_size;
800 thread_exit_only = get_sv("threads::thread_exit_only", TRUE);
801 exit_opt = (SvTRUE(thread_exit_only))
802 ? PERL_ITHR_THREAD_EXIT_ONLY : 0;
805 function_to_call = ST(idx+1);
810 if (hv_exists(specs, "stack", 5)) {
811 stack_size = SvIV(*hv_fetch(specs, "stack", 5, 0));
812 } else if (hv_exists(specs, "stacksize", 9)) {
813 stack_size = SvIV(*hv_fetch(specs, "stacksize", 9, 0));
814 } else if (hv_exists(specs, "stack_size", 10)) {
815 stack_size = SvIV(*hv_fetch(specs, "stack_size", 10, 0));
819 if (hv_exists(specs, "context", 7)) {
820 str = (char *)SvPV_nolen(*hv_fetch(specs, "context", 7, 0));
835 Perl_croak(aTHX_ "Invalid context: %s", str);
837 } else if (hv_exists(specs, "array", 5)) {
838 if (SvTRUE(*hv_fetch(specs, "array", 5, 0))) {
841 } else if (hv_exists(specs, "scalar", 6)) {
842 if (SvTRUE(*hv_fetch(specs, "scalar", 6, 0))) {
845 } else if (hv_exists(specs, "void", 4)) {
846 if (SvTRUE(*hv_fetch(specs, "void", 4, 0))) {
851 /* exit => thread_only */
852 if (hv_exists(specs, "exit", 4)) {
853 str = (char *)SvPV_nolen(*hv_fetch(specs, "exit", 4, 0));
854 exit_opt = (*str == 't' || *str == 'T')
855 ? PERL_ITHR_THREAD_EXIT_ONLY : 0;
859 context = GIMME_V; /* Implicit context */
861 context |= (GIMME_V & (~(G_ARRAY|G_SCALAR|G_VOID)));
867 for (ii=2; ii < items ; ii++) {
868 av_push(params, SvREFCNT_inc(ST(idx+ii)));
873 ST(0) = sv_2mortal(S_ithread_create(aTHX_ Nullsv,
879 newRV_noinc((SV*)params)));
880 /* XSRETURN(1); - implied */
892 /* Class method only */
894 Perl_croak(aTHX_ "Usage: threads->list(...)");
895 classname = (char *)SvPV_nolen(ST(0));
897 /* Calling context */
898 list_context = (GIMME_V == G_ARRAY);
900 /* Running or joinable parameter */
902 want_running = SvTRUE(ST(1));
905 /* Walk through threads list */
906 MUTEX_LOCK(&create_destruct_mutex);
907 for (thread = threads->next;
909 thread = thread->next)
911 /* Ignore detached or joined threads */
912 if (thread->state & (PERL_ITHR_DETACHED|PERL_ITHR_JOINED)) {
916 /* Filter per parameter */
919 if (thread->state & PERL_ITHR_FINISHED) {
920 continue; /* Not running */
923 if (! (thread->state & PERL_ITHR_FINISHED)) {
924 continue; /* Still running - not joinable yet */
929 /* Push object on stack if list context */
931 XPUSHs(sv_2mortal(ithread_to_SV(aTHX_ Nullsv, thread, classname, TRUE)));
935 MUTEX_UNLOCK(&create_destruct_mutex);
936 /* If scalar context, send back count */
937 if (! list_context) {
948 /* Class method only */
950 Perl_croak(aTHX_ "Usage: threads->self()");
951 classname = (char *)SvPV_nolen(ST(0));
953 thread = S_ithread_get(aTHX);
955 ST(0) = sv_2mortal(ithread_to_SV(aTHX_ Nullsv, thread, classname, TRUE));
956 /* XSRETURN(1); - implied */
964 thread = SV_to_ithread(aTHX_ ST(0));
965 XST_mUV(0, thread->tid);
966 /* XSRETURN(1); - implied */
983 /* Object method only */
984 if (! sv_isobject(ST(0)))
985 Perl_croak(aTHX_ "Usage: $thr->join()");
987 /* Check if the thread is joinable */
988 thread = SV_to_ithread(aTHX_ ST(0));
989 MUTEX_LOCK(&thread->mutex);
990 join_err = (thread->state & (PERL_ITHR_DETACHED|PERL_ITHR_JOINED));
991 MUTEX_UNLOCK(&thread->mutex);
993 if (join_err & PERL_ITHR_DETACHED) {
994 Perl_croak(aTHX_ "Cannot join a detached thread");
996 Perl_croak(aTHX_ "Thread already joined");
1000 /* Join the thread */
1002 waitcode = WaitForSingleObject(thread->handle, INFINITE);
1004 pthread_join(thread->thr, &retval);
1007 MUTEX_LOCK(&thread->mutex);
1008 /* Mark as joined */
1009 thread->state |= PERL_ITHR_JOINED;
1011 /* Get the return value from the call_sv */
1014 PerlInterpreter *other_perl;
1015 CLONE_PARAMS clone_params;
1016 ithread *current_thread;
1018 params_copy = (AV *)SvRV(thread->params);
1019 other_perl = thread->interp;
1020 clone_params.stashes = newAV();
1021 clone_params.flags = CLONEf_JOIN_IN;
1022 PL_ptr_table = ptr_table_new();
1023 current_thread = S_ithread_get(aTHX);
1024 S_ithread_set(aTHX_ thread);
1025 /* Ensure 'meaningful' addresses retain their meaning */
1026 ptr_table_store(PL_ptr_table, &other_perl->Isv_undef, &PL_sv_undef);
1027 ptr_table_store(PL_ptr_table, &other_perl->Isv_no, &PL_sv_no);
1028 ptr_table_store(PL_ptr_table, &other_perl->Isv_yes, &PL_sv_yes);
1029 params = (AV *)sv_dup((SV*)params_copy, &clone_params);
1030 S_ithread_set(aTHX_ current_thread);
1031 SvREFCNT_dec(clone_params.stashes);
1032 SvREFCNT_inc(params);
1033 ptr_table_free(PL_ptr_table);
1034 PL_ptr_table = NULL;
1037 /* We are finished with the thread */
1038 S_ithread_clear(aTHX_ thread);
1039 MUTEX_UNLOCK(&thread->mutex);
1041 MUTEX_LOCK(&create_destruct_mutex);
1043 MUTEX_UNLOCK(&create_destruct_mutex);
1045 /* If no return values, then just return */
1050 /* Put return values on stack */
1051 len = (int)AvFILL(params);
1052 for (ii=0; ii <= len; ii++) {
1053 SV* param = av_shift(params);
1054 XPUSHs(sv_2mortal(param));
1057 /* Free return value array */
1058 SvREFCNT_dec(params);
1074 thread = SV_to_ithread(aTHX_ ST(0));
1075 MUTEX_LOCK(&thread->mutex);
1077 /* Check if the thread is detachable */
1078 if ((detach_err = (thread->state & (PERL_ITHR_DETACHED|PERL_ITHR_JOINED)))) {
1079 MUTEX_UNLOCK(&thread->mutex);
1080 if (detach_err & PERL_ITHR_DETACHED) {
1081 Perl_croak(aTHX_ "Thread already detached");
1083 Perl_croak(aTHX_ "Cannot detach a joined thread");
1087 /* Detach the thread */
1088 thread->state |= PERL_ITHR_DETACHED;
1090 /* Windows has no 'detach thread' function */
1092 PERL_THREAD_DETACH(thread->thr);
1094 /* Cleanup if finished */
1095 cleanup = (thread->state & PERL_ITHR_FINISHED);
1096 MUTEX_UNLOCK(&thread->mutex);
1098 MUTEX_LOCK(&create_destruct_mutex);
1105 MUTEX_UNLOCK(&create_destruct_mutex);
1108 S_ithread_destruct(aTHX_ thread);
1119 /* Must have safe signals */
1120 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
1121 Perl_croak(aTHX_ "Cannot signal threads without safe signals");
1123 /* Object method only */
1124 if (! sv_isobject(ST(0)))
1125 Perl_croak(aTHX_ "Usage: $thr->kill('SIG...')");
1128 sig_name = SvPV_nolen(ST(1));
1129 if (isALPHA(*sig_name)) {
1130 if (*sig_name == 'S' && sig_name[1] == 'I' && sig_name[2] == 'G')
1132 if ((signal = whichsig(sig_name)) < 0)
1133 Perl_croak(aTHX_ "Unrecognized signal name: %s", sig_name);
1135 signal = SvIV(ST(1));
1137 /* Set the signal for the thread */
1138 thread = SV_to_ithread(aTHX_ ST(0));
1139 MUTEX_LOCK(&thread->mutex);
1140 if (thread->interp) {
1141 dTHXa(thread->interp);
1142 PL_psig_pend[signal]++;
1145 MUTEX_UNLOCK(&thread->mutex);
1147 /* Return the thread to allow for method chaining */
1149 /* XSRETURN(1); - implied */
1153 ithread_DESTROY(...)
1155 sv_unmagic(SvRV(ST(0)), PERL_MAGIC_shared_scalar);
1163 /* Compares TIDs to determine thread equality */
1164 if (sv_isobject(ST(0)) && sv_isobject(ST(1))) {
1165 ithread *thr1 = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1166 ithread *thr2 = INT2PTR(ithread *, SvIV(SvRV(ST(1))));
1167 are_equal = (thr1->tid == thr2->tid);
1172 /* Return 0 on false for backward compatibility */
1175 /* XSRETURN(1); - implied */
1186 /* Class method only */
1188 Perl_croak(aTHX_ "Usage: threads->object($tid)");
1189 classname = (char *)SvPV_nolen(ST(0));
1191 if ((items < 2) || ! SvOK(ST(1))) {
1195 /* threads->object($tid) */
1198 /* Walk through threads list */
1199 MUTEX_LOCK(&create_destruct_mutex);
1200 for (thread = threads->next;
1202 thread = thread->next)
1204 /* Look for TID, but ignore detached or joined threads */
1205 if ((thread->tid != tid) ||
1206 (thread->state & (PERL_ITHR_DETACHED|PERL_ITHR_JOINED)))
1210 /* Put object on stack */
1211 ST(0) = sv_2mortal(ithread_to_SV(aTHX_ Nullsv, thread, classname, TRUE));
1215 MUTEX_UNLOCK(&create_destruct_mutex);
1219 /* XSRETURN(1); - implied */
1223 ithread__handle(...);
1227 thread = SV_to_ithread(aTHX_ ST(0));
1229 XST_mUV(0, PTR2UV(&thread->handle));
1231 XST_mUV(0, PTR2UV(&thread->thr));
1233 /* XSRETURN(1); - implied */
1237 ithread_get_stack_size(...)
1241 if (sv_isobject(ST(0))) {
1242 /* $thr->get_stack_size() */
1243 ithread *thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1244 stack_size = thread->stack_size;
1246 /* threads->get_stack_size() */
1247 stack_size = default_stack_size;
1249 XST_mIV(0, stack_size);
1250 /* XSRETURN(1); - implied */
1254 ithread_set_stack_size(...)
1259 Perl_croak(aTHX_ "Usage: threads->set_stack_size($size)");
1260 if (sv_isobject(ST(0)))
1261 Perl_croak(aTHX_ "Cannot change stack size of an existing thread");
1263 old_size = default_stack_size;
1264 default_stack_size = good_stack_size(aTHX_ SvIV(ST(1)));
1265 XST_mIV(0, old_size);
1266 /* XSRETURN(1); - implied */
1270 ithread_is_running(...)
1274 /* Object method only */
1275 if (! sv_isobject(ST(0)))
1276 Perl_croak(aTHX_ "Usage: $thr->is_running()");
1278 thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1279 MUTEX_LOCK(&thread->mutex);
1280 ST(0) = (thread->state & PERL_ITHR_FINISHED) ? &PL_sv_no : &PL_sv_yes;
1281 MUTEX_UNLOCK(&thread->mutex);
1282 /* XSRETURN(1); - implied */
1286 ithread_is_detached(...)
1290 thread = SV_to_ithread(aTHX_ ST(0));
1291 MUTEX_LOCK(&thread->mutex);
1292 ST(0) = (thread->state & PERL_ITHR_DETACHED) ? &PL_sv_yes : &PL_sv_no;
1293 MUTEX_UNLOCK(&thread->mutex);
1294 /* XSRETURN(1); - implied */
1298 ithread_is_joinable(...)
1302 /* Object method only */
1303 if (! sv_isobject(ST(0)))
1304 Perl_croak(aTHX_ "Usage: $thr->is_joinable()");
1306 thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1307 MUTEX_LOCK(&thread->mutex);
1308 ST(0) = ((thread->state & PERL_ITHR_FINISHED) &&
1309 ! (thread->state & (PERL_ITHR_DETACHED|PERL_ITHR_JOINED)))
1310 ? &PL_sv_yes : &PL_sv_no;
1311 MUTEX_UNLOCK(&thread->mutex);
1312 /* XSRETURN(1); - implied */
1316 ithread_wantarray(...)
1320 thread = SV_to_ithread(aTHX_ ST(0));
1321 MUTEX_LOCK(&thread->mutex);
1322 ST(0) = (thread->gimme & G_ARRAY) ? &PL_sv_yes :
1323 (thread->gimme & G_VOID) ? &PL_sv_undef
1324 /* G_SCALAR */ : &PL_sv_no;
1325 MUTEX_UNLOCK(&thread->mutex);
1326 /* XSRETURN(1); - implied */
1330 ithread_set_thread_exit_only(...)
1335 Perl_croak(aTHX_ "Usage: ->set_thread_exit_only(boolean)");
1336 thread = SV_to_ithread(aTHX_ ST(0));
1337 MUTEX_LOCK(&thread->mutex);
1338 if (SvTRUE(ST(1))) {
1339 thread->state |= PERL_ITHR_THREAD_EXIT_ONLY;
1341 thread->state &= ~PERL_ITHR_THREAD_EXIT_ONLY;
1343 MUTEX_UNLOCK(&thread->mutex);
1345 #endif /* USE_ITHREADS */
1351 /* The 'main' thread is thread 0.
1352 * It is detached (unjoinable) and immortal.
1358 PL_perl_destruct_level = 2;
1359 MUTEX_INIT(&create_destruct_mutex);
1360 MUTEX_LOCK(&create_destruct_mutex);
1362 PL_threadhook = &Perl_ithread_hook;
1364 thread = (ithread *)PerlMemShared_malloc(sizeof(ithread));
1366 PerlLIO_write(PerlIO_fileno(Perl_error_log), PL_no_mem, strlen(PL_no_mem));
1369 Zero(thread, 1, ithread);
1371 MUTEX_INIT(&thread->mutex);
1373 thread->tid = tid_counter++; /* Thread 0 */
1375 /* Head of the threads list */
1377 thread->next = thread;
1378 thread->prev = thread;
1380 thread->count = 1; /* Immortal */
1382 thread->interp = aTHX;
1383 thread->state = PERL_ITHR_DETACHED; /* Detached */
1384 thread->stack_size = default_stack_size;
1386 thread->thr = GetCurrentThreadId();
1388 thread->thr = pthread_self();
1391 S_ithread_set(aTHX_ thread);
1392 MUTEX_UNLOCK(&create_destruct_mutex);
1393 #endif /* USE_ITHREADS */