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::_cxt" XS_VERSION
78 /* Used by Perl interpreter for thread context switching */
85 #define MY_POOL_KEY "threads::_pool" XS_VERSION
88 /* Structure for 'main' thread
89 * Also forms the 'base' for the doubly-linked list of threads */
92 /* Protects the creation and destruction of threads*/
93 perl_mutex create_destruct_mutex;
99 IV default_stack_size;
104 SV *my_pool_sv = *hv_fetch(PL_modglobal, MY_POOL_KEY, \
105 sizeof(MY_POOL_KEY)-1, TRUE); \
106 my_pool_t *my_poolp = INT2PTR(my_pool_t*, SvUV(my_pool_sv))
108 #define MY_POOL (*my_poolp)
111 /* Used by Perl interpreter for thread context switching */
113 S_ithread_set(pTHX_ ithread *thread)
116 MY_CXT.context = thread;
123 return (MY_CXT.context);
127 /* Free any data (such as the Perl interpreter) attached to an ithread
128 * structure. This is a bit like undef on SVs, where the SV isn't freed,
129 * but the PVX is. Must be called with thread->mutex already held.
132 S_ithread_clear(pTHX_ ithread *thread)
134 PerlInterpreter *interp;
136 assert((thread->state & PERL_ITHR_FINISHED) &&
137 (thread->state & (PERL_ITHR_DETACHED|PERL_ITHR_JOINED)));
139 interp = thread->interp;
143 PERL_SET_CONTEXT(interp);
144 S_ithread_set(aTHX_ thread);
146 SvREFCNT_dec(thread->params);
147 thread->params = Nullsv;
149 perl_destruct(interp);
151 thread->interp = NULL;
154 PERL_SET_CONTEXT(aTHX);
158 /* Free an ithread structure and any attached data if its count == 0 */
160 S_ithread_destruct(pTHX_ ithread *thread)
167 /* Return if thread is still being used */
168 if (thread->count != 0) {
172 /* Main thread (0) is immortal and should never get here */
173 assert(thread->tid != 0);
175 /* Remove from circular list of threads */
176 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
177 thread->next->prev = thread->prev;
178 thread->prev->next = thread->next;
181 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
183 /* Thread is now disowned */
184 MUTEX_LOCK(&thread->mutex);
185 S_ithread_clear(aTHX_ thread);
188 handle = thread->handle;
189 thread->handle = NULL;
191 MUTEX_UNLOCK(&thread->mutex);
192 MUTEX_DESTROY(&thread->mutex);
200 /* Call PerlMemShared_free() in the context of the "first" interpreter
201 * per http://www.nntp.perl.org/group/perl.perl5.porters/110772
203 aTHX = MY_POOL.main_thread.interp;
204 PerlMemShared_free(thread);
208 /* Warn if exiting with any unjoined threads */
216 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
217 veto_cleanup = (MY_POOL.running_threads || MY_POOL.joinable_threads);
218 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
221 if (ckWARN_d(WARN_THREADS)) {
222 Perl_warn(aTHX_ "Perl exited with active threads:\n\t%"
223 IVdf " running and unjoined\n\t%"
224 IVdf " finished and unjoined\n\t%"
225 IVdf " running and detached\n",
226 MY_POOL.running_threads,
227 MY_POOL.joinable_threads,
228 MY_POOL.detached_threads);
232 return (veto_cleanup);
235 /* Called on exit from main thread */
237 Perl_ithread_hook(pTHX)
241 int veto_cleanup = 0;
243 if (aTHX == MY_POOL.main_thread.interp) {
244 veto_cleanup = S_exit_warning(aTHX);
245 if (! veto_cleanup) {
246 MUTEX_DESTROY(&MY_POOL.create_destruct_mutex);
250 return (veto_cleanup);
254 /* MAGIC (in mg.h sense) hooks */
257 ithread_mg_get(pTHX_ SV *sv, MAGIC *mg)
259 ithread *thread = (ithread *)mg->mg_ptr;
260 SvIV_set(sv, PTR2IV(thread));
266 ithread_mg_free(pTHX_ SV *sv, MAGIC *mg)
268 ithread *thread = (ithread *)mg->mg_ptr;
271 MUTEX_LOCK(&thread->mutex);
272 cleanup = ((--thread->count == 0) &&
273 (thread->state & PERL_ITHR_FINISHED) &&
274 (thread->state & (PERL_ITHR_DETACHED|PERL_ITHR_JOINED)));
275 MUTEX_UNLOCK(&thread->mutex);
278 S_ithread_destruct(aTHX_ thread);
284 ithread_mg_dup(pTHX_ MAGIC *mg, CLONE_PARAMS *param)
286 ithread *thread = (ithread *)mg->mg_ptr;
287 MUTEX_LOCK(&thread->mutex);
289 MUTEX_UNLOCK(&thread->mutex);
293 MGVTBL ithread_vtbl = {
294 ithread_mg_get, /* get */
298 ithread_mg_free, /* free */
300 ithread_mg_dup /* dup */
304 /* Provided default, minimum and rational stack sizes */
306 S_good_stack_size(pTHX_ IV stack_size)
310 /* Use default stack size if no stack size specified */
312 return (MY_POOL.default_stack_size);
315 #ifdef PTHREAD_STACK_MIN
316 /* Can't use less than minimum */
317 if (stack_size < PTHREAD_STACK_MIN) {
318 if (ckWARN(WARN_THREADS)) {
319 Perl_warn(aTHX_ "Using minimum thread stack size of %" IVdf, (IV)PTHREAD_STACK_MIN);
321 return (PTHREAD_STACK_MIN);
325 /* Round up to page size boundary */
326 if (MY_POOL.page_size <= 0) {
327 #if defined(HAS_SYSCONF) && (defined(_SC_PAGESIZE) || defined(_SC_MMAP_PAGE_SIZE))
328 SETERRNO(0, SS_NORMAL);
330 MY_POOL.page_size = sysconf(_SC_PAGESIZE);
332 MY_POOL.page_size = sysconf(_SC_MMAP_PAGE_SIZE);
334 if ((long)MY_POOL.page_size < 0) {
336 SV * const error = get_sv("@", FALSE);
337 (void)SvUPGRADE(error, SVt_PV);
338 Perl_croak(aTHX_ "PANIC: sysconf: %s", SvPV_nolen(error));
340 Perl_croak(aTHX_ "PANIC: sysconf: pagesize unknown");
344 # ifdef HAS_GETPAGESIZE
345 MY_POOL.page_size = getpagesize();
347 # if defined(I_SYS_PARAM) && defined(PAGESIZE)
348 MY_POOL.page_size = PAGESIZE;
350 MY_POOL.page_size = 8192; /* A conservative default */
353 if (MY_POOL.page_size <= 0) {
354 Perl_croak(aTHX_ "PANIC: bad pagesize %" IVdf, (IV)MY_POOL.page_size);
358 stack_size = ((stack_size + (MY_POOL.page_size - 1)) / MY_POOL.page_size) * MY_POOL.page_size;
364 /* Starts executing the thread.
365 * Passed as the C level function to run in the new thread.
368 STATIC THREAD_RET_TYPE
369 S_ithread_run(LPVOID arg)
372 S_ithread_run(void * arg)
375 ithread *thread = (ithread *)arg;
384 dTHXa(thread->interp);
388 /* Blocked until ->create() call finishes */
389 MUTEX_LOCK(&thread->mutex);
390 MUTEX_UNLOCK(&thread->mutex);
392 PERL_SET_CONTEXT(thread->interp);
393 S_ithread_set(aTHX_ thread);
395 PL_perl_destruct_level = 2;
398 AV *params = (AV *)SvRV(thread->params);
399 int len = (int)av_len(params)+1;
406 /* Put args on the stack */
408 for (ii=0; ii < len; ii++) {
409 XPUSHs(av_shift(params));
413 oldscope = PL_scopestack_ix;
416 /* Run the specified function */
417 len = (int)call_sv(thread->init_function, thread->gimme|G_EVAL);
418 } else if (jmp_rc == 2) {
421 exit_code = STATUS_CURRENT;
422 while (PL_scopestack_ix > oldscope) {
428 /* Remove args from stack and put back in params array */
430 for (ii=len-1; ii >= 0; ii--) {
433 av_store(params, ii, SvREFCNT_inc(sv));
440 /* Check for failure */
441 if (SvTRUE(ERRSV) && ckWARN_d(WARN_THREADS)) {
442 oldscope = PL_scopestack_ix;
445 /* Warn that thread died */
446 Perl_warn(aTHX_ "Thread %" UVuf " terminated abnormally: %" SVf, thread->tid, ERRSV);
447 } else if (jmp_rc == 2) {
448 /* Warn handler exited */
450 exit_code = STATUS_CURRENT;
451 while (PL_scopestack_ix > oldscope) {
458 /* Release function ref */
459 SvREFCNT_dec(thread->init_function);
460 thread->init_function = Nullsv;
463 PerlIO_flush((PerlIO *)NULL);
465 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
466 MUTEX_LOCK(&thread->mutex);
467 /* Mark as finished */
468 thread->state |= PERL_ITHR_FINISHED;
469 /* Clear exit flag if required */
470 if (thread->state & PERL_ITHR_THREAD_EXIT_ONLY) {
473 /* Cleanup if detached */
474 cleanup = (thread->state & PERL_ITHR_DETACHED);
475 MUTEX_UNLOCK(&thread->mutex);
477 /* Adjust thread status counts */
479 MY_POOL.detached_threads--;
481 MY_POOL.running_threads--;
482 MY_POOL.joinable_threads++;
484 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
486 /* Exit application if required */
488 oldscope = PL_scopestack_ix;
491 /* Warn if there are unjoined threads */
492 S_exit_warning(aTHX);
493 } else if (jmp_rc == 2) {
494 /* Warn handler exited */
495 exit_code = STATUS_CURRENT;
496 while (PL_scopestack_ix > oldscope) {
505 /* Clean up detached thread */
507 S_ithread_destruct(aTHX_ thread);
518 /* Type conversion helper functions */
521 S_ithread_to_SV(pTHX_ SV *obj, ithread *thread, char *classname, bool inc)
526 /* If incrementing thread ref count, then call within mutex lock */
528 MUTEX_LOCK(&thread->mutex);
530 MUTEX_UNLOCK(&thread->mutex);
537 sv = newSVrv(obj, classname);
538 sv_setiv(sv, PTR2IV(thread));
539 mg = sv_magicext(sv, Nullsv, PERL_MAGIC_shared_scalar, &ithread_vtbl, (char *)thread, 0);
540 mg->mg_flags |= MGf_DUP;
547 S_SV_to_ithread(pTHX_ SV *sv)
549 /* Argument is a thread */
551 return (INT2PTR(ithread *, SvIV(SvRV(sv))));
553 /* Argument is classname, therefore return current thread */
554 return (S_ithread_get(aTHX));
559 * Called in context of parent thread.
560 * Called with MY_POOL.create_destruct_mutex locked. (Unlocked on error.)
564 pTHX_ SV *init_function,
573 CLONE_PARAMS clone_param;
574 ithread *current_thread = S_ithread_get(aTHX);
576 SV **tmps_tmp = PL_tmps_stack;
577 IV tmps_ix = PL_tmps_ix;
579 int rc_stack_size = 0;
580 int rc_thread_create = 0;
583 /* Allocate thread structure in context of the main threads interpreter */
585 PERL_SET_CONTEXT(MY_POOL.main_thread.interp);
586 thread = (ithread *)PerlMemShared_malloc(sizeof(ithread));
588 PERL_SET_CONTEXT(aTHX);
590 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
591 PerlLIO_write(PerlIO_fileno(Perl_error_log), PL_no_mem, strlen(PL_no_mem));
594 Zero(thread, 1, ithread);
596 /* Add to threads list */
597 thread->next = &MY_POOL.main_thread;
598 thread->prev = MY_POOL.main_thread.prev;
599 MY_POOL.main_thread.prev = thread;
600 thread->prev->next = thread;
602 /* Set count to 1 immediately in case thread exits before
603 * we return to caller!
607 /* Block new thread until ->create() call finishes */
608 MUTEX_INIT(&thread->mutex);
609 MUTEX_LOCK(&thread->mutex);
611 thread->tid = MY_POOL.tid_counter++;
612 thread->stack_size = S_good_stack_size(aTHX_ stack_size);
613 thread->gimme = gimme;
614 thread->state = exit_opt;
616 /* "Clone" our interpreter into the thread's interpreter.
617 * This gives thread access to "static data" and code.
619 PerlIO_flush((PerlIO *)NULL);
620 S_ithread_set(aTHX_ thread);
622 SAVEBOOL(PL_srand_called); /* Save this so it becomes the correct value */
623 PL_srand_called = FALSE; /* Set it to false so we can detect if it gets
624 set during the clone */
627 thread->interp = perl_clone(aTHX, CLONEf_KEEP_PTR_TABLE | CLONEf_CLONE_HOST);
629 thread->interp = perl_clone(aTHX, CLONEf_KEEP_PTR_TABLE);
632 /* perl_clone() leaves us in new interpreter's context. As it is tricky
633 * to spot an implicit aTHX, create a new scope with aTHX matching the
634 * context for the duration of our work for new interpreter.
637 dTHXa(thread->interp);
641 /* Here we remove END blocks since they should only run in the thread
644 SvREFCNT_dec(PL_endav);
647 if (SvPOK(init_function)) {
648 thread->init_function = newSV(0);
649 sv_copypv(thread->init_function, init_function);
651 clone_param.flags = 0;
652 thread->init_function = sv_dup(init_function, &clone_param);
653 if (SvREFCNT(thread->init_function) == 0) {
654 SvREFCNT_inc_void(thread->init_function);
658 thread->params = sv_dup(params, &clone_param);
659 SvREFCNT_inc_void(thread->params);
661 /* The code below checks that anything living on the tmps stack and
662 * has been cloned (so it lives in the ptr_table) has a refcount
665 * If the refcount is 0 it means that a something on the stack/context
666 * was holding a reference to it and since we init_stacks() in
667 * perl_clone that won't get cleaned and we will get a leaked scalar.
668 * The reason it was cloned was that it lived on the @_ stack.
670 * Example of this can be found in bugreport 15837 where calls in the
671 * parameter list end up as a temp.
673 * One could argue that this fix should be in perl_clone.
675 while (tmps_ix > 0) {
676 SV* sv = (SV*)ptr_table_fetch(PL_ptr_table, tmps_tmp[tmps_ix]);
678 if (sv && SvREFCNT(sv) == 0) {
679 SvREFCNT_inc_void(sv);
684 SvTEMP_off(thread->init_function);
685 ptr_table_free(PL_ptr_table);
687 PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
689 S_ithread_set(aTHX_ current_thread);
690 PERL_SET_CONTEXT(aTHX);
692 /* Create/start the thread */
694 thread->handle = CreateThread(NULL,
695 (DWORD)thread->stack_size,
698 STACK_SIZE_PARAM_IS_A_RESERVATION,
702 STATIC pthread_attr_t attr;
703 STATIC int attr_inited = 0;
704 STATIC int attr_joinable = PTHREAD_CREATE_JOINABLE;
706 pthread_attr_init(&attr);
710 # ifdef PTHREAD_ATTR_SETDETACHSTATE
711 /* Threads start out joinable */
712 PTHREAD_ATTR_SETDETACHSTATE(&attr, attr_joinable);
715 # ifdef _POSIX_THREAD_ATTR_STACKSIZE
716 /* Set thread's stack size */
717 if (thread->stack_size > 0) {
718 rc_stack_size = pthread_attr_setstacksize(&attr, (size_t)thread->stack_size);
722 /* Create the thread */
723 if (! rc_stack_size) {
724 # ifdef OLD_PTHREADS_API
725 rc_thread_create = pthread_create(&thread->thr,
730 # if defined(HAS_PTHREAD_ATTR_SETSCOPE) && defined(PTHREAD_SCOPE_SYSTEM)
731 pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);
733 rc_thread_create = pthread_create(&thread->thr,
740 # ifdef _POSIX_THREAD_ATTR_STACKSIZE
741 /* Try to get thread's actual stack size */
745 stacksize = pthread_attr_getstacksize(attr);
747 if (! pthread_attr_getstacksize(&attr, &stacksize))
750 thread->stack_size = (IV)stacksize;
757 /* Check for errors */
759 if (thread->handle == NULL) {
761 if (rc_stack_size || rc_thread_create) {
763 /* Must unlock mutex for destruct call */
764 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
766 S_ithread_destruct(aTHX_ thread);
768 if (ckWARN_d(WARN_THREADS)) {
770 Perl_warn(aTHX_ "Thread creation failed: pthread_attr_setstacksize(%" IVdf ") returned %d", thread->stack_size, rc_stack_size);
772 Perl_warn(aTHX_ "Thread creation failed: pthread_create returned %d", rc_thread_create);
779 MY_POOL.running_threads++;
784 #endif /* USE_ITHREADS */
787 MODULE = threads PACKAGE = threads PREFIX = ithread_
797 SV *function_to_call;
803 SV *thread_exit_only;
809 if ((items >= 2) && SvROK(ST(1)) && SvTYPE(SvRV(ST(1)))==SVt_PVHV) {
811 Perl_croak(aTHX_ "Usage: threads->create(\\%specs, function, ...)");
813 specs = (HV*)SvRV(ST(1));
817 Perl_croak(aTHX_ "Usage: threads->create(function, ...)");
823 if (sv_isobject(ST(0))) {
825 classname = HvNAME(SvSTASH(SvRV(ST(0))));
826 thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
827 stack_size = thread->stack_size;
828 exit_opt = thread->state & PERL_ITHR_THREAD_EXIT_ONLY;
830 /* threads->create() */
831 classname = (char *)SvPV_nolen(ST(0));
832 stack_size = MY_POOL.default_stack_size;
833 thread_exit_only = get_sv("threads::thread_exit_only", TRUE);
834 exit_opt = (SvTRUE(thread_exit_only))
835 ? PERL_ITHR_THREAD_EXIT_ONLY : 0;
838 function_to_call = ST(idx+1);
843 if (hv_exists(specs, "stack", 5)) {
844 stack_size = SvIV(*hv_fetch(specs, "stack", 5, 0));
845 } else if (hv_exists(specs, "stacksize", 9)) {
846 stack_size = SvIV(*hv_fetch(specs, "stacksize", 9, 0));
847 } else if (hv_exists(specs, "stack_size", 10)) {
848 stack_size = SvIV(*hv_fetch(specs, "stack_size", 10, 0));
852 if (hv_exists(specs, "context", 7)) {
853 str = (char *)SvPV_nolen(*hv_fetch(specs, "context", 7, 0));
868 Perl_croak(aTHX_ "Invalid context: %s", str);
870 } else if (hv_exists(specs, "array", 5)) {
871 if (SvTRUE(*hv_fetch(specs, "array", 5, 0))) {
874 } else if (hv_exists(specs, "scalar", 6)) {
875 if (SvTRUE(*hv_fetch(specs, "scalar", 6, 0))) {
878 } else if (hv_exists(specs, "void", 4)) {
879 if (SvTRUE(*hv_fetch(specs, "void", 4, 0))) {
884 /* exit => thread_only */
885 if (hv_exists(specs, "exit", 4)) {
886 str = (char *)SvPV_nolen(*hv_fetch(specs, "exit", 4, 0));
887 exit_opt = (*str == 't' || *str == 'T')
888 ? PERL_ITHR_THREAD_EXIT_ONLY : 0;
892 context = GIMME_V; /* Implicit context */
894 context |= (GIMME_V & (~(G_ARRAY|G_SCALAR|G_VOID)));
900 for (ii=2; ii < items ; ii++) {
901 av_push(params, SvREFCNT_inc(ST(idx+ii)));
906 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
907 thread = S_ithread_create(aTHX_ function_to_call,
911 newRV_noinc((SV*)params));
913 XSRETURN_UNDEF; /* Mutex already unlocked */
915 ST(0) = sv_2mortal(S_ithread_to_SV(aTHX_ Nullsv, thread, classname, FALSE));
918 MUTEX_UNLOCK(&thread->mutex);
919 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
921 /* XSRETURN(1); - implied */
934 /* Class method only */
936 Perl_croak(aTHX_ "Usage: threads->list(...)");
938 classname = (char *)SvPV_nolen(ST(0));
940 /* Calling context */
941 list_context = (GIMME_V == G_ARRAY);
943 /* Running or joinable parameter */
945 want_running = SvTRUE(ST(1));
948 /* Walk through threads list */
949 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
950 for (thread = MY_POOL.main_thread.next;
951 thread != &MY_POOL.main_thread;
952 thread = thread->next)
954 /* Ignore detached or joined threads */
955 if (thread->state & (PERL_ITHR_DETACHED|PERL_ITHR_JOINED)) {
959 /* Filter per parameter */
962 if (thread->state & PERL_ITHR_FINISHED) {
963 continue; /* Not running */
966 if (! (thread->state & PERL_ITHR_FINISHED)) {
967 continue; /* Still running - not joinable yet */
972 /* Push object on stack if list context */
974 XPUSHs(sv_2mortal(S_ithread_to_SV(aTHX_ Nullsv, thread, classname, TRUE)));
978 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
979 /* If scalar context, send back count */
980 if (! list_context) {
991 /* Class method only */
993 Perl_croak(aTHX_ "Usage: threads->self()");
995 classname = (char *)SvPV_nolen(ST(0));
997 thread = S_ithread_get(aTHX);
999 ST(0) = sv_2mortal(S_ithread_to_SV(aTHX_ Nullsv, thread, classname, TRUE));
1000 /* XSRETURN(1); - implied */
1008 thread = S_SV_to_ithread(aTHX_ ST(0));
1009 XST_mUV(0, thread->tid);
1010 /* XSRETURN(1); - implied */
1028 /* Object method only */
1029 if (! sv_isobject(ST(0))) {
1030 Perl_croak(aTHX_ "Usage: $thr->join()");
1033 /* Check if the thread is joinable */
1034 thread = S_SV_to_ithread(aTHX_ ST(0));
1035 join_err = (thread->state & (PERL_ITHR_DETACHED|PERL_ITHR_JOINED));
1037 if (join_err & PERL_ITHR_DETACHED) {
1038 Perl_croak(aTHX_ "Cannot join a detached thread");
1040 Perl_croak(aTHX_ "Thread already joined");
1044 /* Join the thread */
1046 waitcode = WaitForSingleObject(thread->handle, INFINITE);
1048 pthread_join(thread->thr, &retval);
1051 MUTEX_LOCK(&thread->mutex);
1052 /* Mark as joined */
1053 thread->state |= PERL_ITHR_JOINED;
1055 /* Get the return value from the call_sv */
1058 PerlInterpreter *other_perl;
1059 CLONE_PARAMS clone_params;
1060 ithread *current_thread;
1062 params_copy = (AV *)SvRV(thread->params);
1063 other_perl = thread->interp;
1064 clone_params.stashes = newAV();
1065 clone_params.flags = CLONEf_JOIN_IN;
1066 PL_ptr_table = ptr_table_new();
1067 current_thread = S_ithread_get(aTHX);
1068 S_ithread_set(aTHX_ thread);
1069 /* Ensure 'meaningful' addresses retain their meaning */
1070 ptr_table_store(PL_ptr_table, &other_perl->Isv_undef, &PL_sv_undef);
1071 ptr_table_store(PL_ptr_table, &other_perl->Isv_no, &PL_sv_no);
1072 ptr_table_store(PL_ptr_table, &other_perl->Isv_yes, &PL_sv_yes);
1073 params = (AV *)sv_dup((SV*)params_copy, &clone_params);
1074 S_ithread_set(aTHX_ current_thread);
1075 SvREFCNT_dec(clone_params.stashes);
1076 SvREFCNT_inc_void(params);
1077 ptr_table_free(PL_ptr_table);
1078 PL_ptr_table = NULL;
1081 /* We are finished with the thread */
1082 S_ithread_clear(aTHX_ thread);
1083 MUTEX_UNLOCK(&thread->mutex);
1085 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
1086 if (! (thread->state & PERL_ITHR_DETACHED)) {
1087 MY_POOL.joinable_threads--;
1089 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
1091 /* If no return values, then just return */
1096 /* Put return values on stack */
1097 len = (int)AvFILL(params);
1098 for (ii=0; ii <= len; ii++) {
1099 SV* param = av_shift(params);
1100 XPUSHs(sv_2mortal(param));
1103 /* Free return value array */
1104 SvREFCNT_dec(params);
1121 /* Check if the thread is detachable */
1122 thread = S_SV_to_ithread(aTHX_ ST(0));
1123 if ((detach_err = (thread->state & (PERL_ITHR_DETACHED|PERL_ITHR_JOINED)))) {
1124 if (detach_err & PERL_ITHR_DETACHED) {
1125 Perl_croak(aTHX_ "Thread already detached");
1127 Perl_croak(aTHX_ "Cannot detach a joined thread");
1131 /* Detach the thread */
1132 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
1133 MUTEX_LOCK(&thread->mutex);
1134 thread->state |= PERL_ITHR_DETACHED;
1136 /* Windows has no 'detach thread' function */
1138 PERL_THREAD_DETACH(thread->thr);
1140 /* Cleanup if finished */
1141 cleanup = (thread->state & PERL_ITHR_FINISHED);
1142 MUTEX_UNLOCK(&thread->mutex);
1145 MY_POOL.joinable_threads--;
1147 MY_POOL.running_threads--;
1148 MY_POOL.detached_threads++;
1150 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
1153 S_ithread_destruct(aTHX_ thread);
1164 /* Must have safe signals */
1165 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG) {
1166 Perl_croak(aTHX_ "Cannot signal threads without safe signals");
1169 /* Object method only */
1170 if (! sv_isobject(ST(0))) {
1171 Perl_croak(aTHX_ "Usage: $thr->kill('SIG...')");
1175 sig_name = SvPV_nolen(ST(1));
1176 if (isALPHA(*sig_name)) {
1177 if (*sig_name == 'S' && sig_name[1] == 'I' && sig_name[2] == 'G') {
1180 if ((signal = whichsig(sig_name)) < 0) {
1181 Perl_croak(aTHX_ "Unrecognized signal name: %s", sig_name);
1184 signal = SvIV(ST(1));
1187 /* Set the signal for the thread */
1188 thread = S_SV_to_ithread(aTHX_ ST(0));
1189 MUTEX_LOCK(&thread->mutex);
1190 if (thread->interp) {
1191 dTHXa(thread->interp);
1192 PL_psig_pend[signal]++;
1195 MUTEX_UNLOCK(&thread->mutex);
1197 /* Return the thread to allow for method chaining */
1199 /* XSRETURN(1); - implied */
1203 ithread_DESTROY(...)
1205 sv_unmagic(SvRV(ST(0)), PERL_MAGIC_shared_scalar);
1213 /* Compares TIDs to determine thread equality */
1214 if (sv_isobject(ST(0)) && sv_isobject(ST(1))) {
1215 ithread *thr1 = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1216 ithread *thr2 = INT2PTR(ithread *, SvIV(SvRV(ST(1))));
1217 are_equal = (thr1->tid == thr2->tid);
1222 /* Return 0 on false for backward compatibility */
1225 /* XSRETURN(1); - implied */
1237 /* Class method only */
1239 Perl_croak(aTHX_ "Usage: threads->object($tid)");
1241 classname = (char *)SvPV_nolen(ST(0));
1243 if ((items < 2) || ! SvOK(ST(1))) {
1247 /* threads->object($tid) */
1250 /* Walk through threads list */
1251 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
1252 for (thread = MY_POOL.main_thread.next;
1253 thread != &MY_POOL.main_thread;
1254 thread = thread->next)
1257 if (thread->tid == tid) {
1258 /* Ignore if detached or joined */
1259 if (! (thread->state & (PERL_ITHR_DETACHED|PERL_ITHR_JOINED))) {
1260 /* Put object on stack */
1261 ST(0) = sv_2mortal(S_ithread_to_SV(aTHX_ Nullsv, thread, classname, TRUE));
1267 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
1272 /* XSRETURN(1); - implied */
1276 ithread__handle(...);
1280 thread = S_SV_to_ithread(aTHX_ ST(0));
1282 XST_mUV(0, PTR2UV(&thread->handle));
1284 XST_mUV(0, PTR2UV(&thread->thr));
1286 /* XSRETURN(1); - implied */
1290 ithread_get_stack_size(...)
1295 if (sv_isobject(ST(0))) {
1296 /* $thr->get_stack_size() */
1297 ithread *thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1298 stack_size = thread->stack_size;
1300 /* threads->get_stack_size() */
1301 stack_size = MY_POOL.default_stack_size;
1303 XST_mIV(0, stack_size);
1304 /* XSRETURN(1); - implied */
1308 ithread_set_stack_size(...)
1314 Perl_croak(aTHX_ "Usage: threads->set_stack_size($size)");
1316 if (sv_isobject(ST(0))) {
1317 Perl_croak(aTHX_ "Cannot change stack size of an existing thread");
1320 old_size = MY_POOL.default_stack_size;
1321 MY_POOL.default_stack_size = S_good_stack_size(aTHX_ SvIV(ST(1)));
1322 XST_mIV(0, old_size);
1323 /* XSRETURN(1); - implied */
1327 ithread_is_running(...)
1331 /* Object method only */
1332 if (! sv_isobject(ST(0))) {
1333 Perl_croak(aTHX_ "Usage: $thr->is_running()");
1336 thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1337 ST(0) = (thread->state & PERL_ITHR_FINISHED) ? &PL_sv_no : &PL_sv_yes;
1338 /* XSRETURN(1); - implied */
1342 ithread_is_detached(...)
1346 thread = S_SV_to_ithread(aTHX_ ST(0));
1347 ST(0) = (thread->state & PERL_ITHR_DETACHED) ? &PL_sv_yes : &PL_sv_no;
1348 /* XSRETURN(1); - implied */
1352 ithread_is_joinable(...)
1356 /* Object method only */
1357 if (! sv_isobject(ST(0))) {
1358 Perl_croak(aTHX_ "Usage: $thr->is_joinable()");
1361 thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1362 MUTEX_LOCK(&thread->mutex);
1363 ST(0) = ((thread->state & PERL_ITHR_FINISHED) &&
1364 ! (thread->state & (PERL_ITHR_DETACHED|PERL_ITHR_JOINED)))
1365 ? &PL_sv_yes : &PL_sv_no;
1366 MUTEX_UNLOCK(&thread->mutex);
1367 /* XSRETURN(1); - implied */
1371 ithread_wantarray(...)
1375 thread = S_SV_to_ithread(aTHX_ ST(0));
1376 ST(0) = (thread->gimme & G_ARRAY) ? &PL_sv_yes :
1377 (thread->gimme & G_VOID) ? &PL_sv_undef
1378 /* G_SCALAR */ : &PL_sv_no;
1379 /* XSRETURN(1); - implied */
1383 ithread_set_thread_exit_only(...)
1388 Perl_croak(aTHX_ "Usage: ->set_thread_exit_only(boolean)");
1390 thread = S_SV_to_ithread(aTHX_ ST(0));
1391 MUTEX_LOCK(&thread->mutex);
1392 if (SvTRUE(ST(1))) {
1393 thread->state |= PERL_ITHR_THREAD_EXIT_ONLY;
1395 thread->state &= ~PERL_ITHR_THREAD_EXIT_ONLY;
1397 MUTEX_UNLOCK(&thread->mutex);
1399 #endif /* USE_ITHREADS */
1405 SV *my_pool_sv = *hv_fetch(PL_modglobal, MY_POOL_KEY,
1406 sizeof(MY_POOL_KEY)-1, TRUE);
1407 my_pool_t *my_poolp = (my_pool_t*)SvPVX(newSV(sizeof(my_pool_t)-1));
1411 Zero(my_poolp, 1, my_pool_t);
1412 sv_setuv(my_pool_sv, PTR2UV(my_poolp));
1414 PL_perl_destruct_level = 2;
1415 MUTEX_INIT(&MY_POOL.create_destruct_mutex);
1416 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
1418 PL_threadhook = &Perl_ithread_hook;
1420 MY_POOL.tid_counter = 1;
1421 # ifdef THREAD_CREATE_NEEDS_STACK
1422 MY_POOL.default_stack_size = THREAD_CREATE_NEEDS_STACK;
1425 /* The 'main' thread is thread 0.
1426 * It is detached (unjoinable) and immortal.
1429 MUTEX_INIT(&MY_POOL.main_thread.mutex);
1431 /* Head of the threads list */
1432 MY_POOL.main_thread.next = &MY_POOL.main_thread;
1433 MY_POOL.main_thread.prev = &MY_POOL.main_thread;
1435 MY_POOL.main_thread.count = 1; /* Immortal */
1437 MY_POOL.main_thread.interp = aTHX;
1438 MY_POOL.main_thread.state = PERL_ITHR_DETACHED; /* Detached */
1439 MY_POOL.main_thread.stack_size = MY_POOL.default_stack_size;
1441 MY_POOL.main_thread.thr = GetCurrentThreadId();
1443 MY_POOL.main_thread.thr = pthread_self();
1446 S_ithread_set(aTHX_ &MY_POOL.main_thread);
1447 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
1448 #endif /* USE_ITHREADS */