1 #define PERL_NO_GET_CONTEXT
5 /* Workaround for XSUB.h bug under WIN32 */
8 # if !defined(__BORLANDC__)
9 # define setjmp(x) _setjmp(x)
13 # define NEED_PL_signals
14 # define NEED_newRV_noinc
15 # define NEED_sv_2pv_nolen
24 /* Supposed to be in Winbase.h */
25 # ifndef STACK_SIZE_PARAM_IS_A_RESERVATION
26 # define STACK_SIZE_PARAM_IS_A_RESERVATION 0x00010000
28 # include <win32thread.h>
31 typedef perl_os_thread pthread_t;
36 # define PERL_THREAD_SETSPECIFIC(k,v) pthread_setspecific(k,v)
37 # ifdef OLD_PTHREADS_API
38 # define PERL_THREAD_DETACH(t) pthread_detach(&(t))
40 # define PERL_THREAD_DETACH(t) pthread_detach((t))
43 #if !defined(HAS_GETPAGESIZE) && defined(I_SYS_PARAM)
44 # include <sys/param.h>
47 /* Values for 'state' member */
48 #define PERL_ITHR_DETACHED 1 /* Thread has been detached */
49 #define PERL_ITHR_JOINED 2 /* Thread has been joined */
50 #define PERL_ITHR_FINISHED 4 /* Thread has finished execution */
51 #define PERL_ITHR_THREAD_EXIT_ONLY 8 /* exit() only exits current thread */
52 #define PERL_ITHR_NONVIABLE 16 /* Thread creation failed */
53 #define PERL_ITHR_DIED 32 /* Thread finished by dying */
55 #define PERL_ITHR_UNCALLABLE (PERL_ITHR_DETACHED|PERL_ITHR_JOINED)
58 typedef struct _ithread {
59 struct _ithread *next; /* Next thread in the list */
60 struct _ithread *prev; /* Prev thread in the list */
61 PerlInterpreter *interp; /* The threads interpreter */
62 UV tid; /* Threads module's thread id */
63 perl_mutex mutex; /* Mutex for updating things in this struct */
64 int count; /* Reference count. See S_ithread_create. */
65 int state; /* Detached, joined, finished, etc. */
66 int gimme; /* Context of create */
67 SV *init_function; /* Code to run */
68 SV *params; /* Args to pass function */
70 DWORD thr; /* OS's idea if thread id */
71 HANDLE handle; /* OS's waitable handle */
73 pthread_t thr; /* OS's handle for the thread */
76 SV *err; /* Error from abnormally terminated thread */
77 char *err_class; /* Error object's classname if applicable */
81 #define MY_CXT_KEY "threads::_cxt" XS_VERSION
84 /* Used by Perl interpreter for thread context switching */
91 #define MY_POOL_KEY "threads::_pool" XS_VERSION
94 /* Structure for 'main' thread
95 * Also forms the 'base' for the doubly-linked list of threads */
98 /* Protects the creation and destruction of threads*/
99 perl_mutex create_destruct_mutex;
106 IV default_stack_size;
111 SV *my_pool_sv = *hv_fetch(PL_modglobal, MY_POOL_KEY, \
112 sizeof(MY_POOL_KEY)-1, TRUE); \
113 my_pool_t *my_poolp = INT2PTR(my_pool_t*, SvUV(my_pool_sv))
115 #define MY_POOL (*my_poolp)
118 /* Used by Perl interpreter for thread context switching */
120 S_ithread_set(pTHX_ ithread *thread)
123 MY_CXT.context = thread;
130 return (MY_CXT.context);
134 /* Free any data (such as the Perl interpreter) attached to an ithread
135 * structure. This is a bit like undef on SVs, where the SV isn't freed,
136 * but the PVX is. Must be called with thread->mutex already locked. Also,
137 * must be called with MY_POOL.create_destruct_mutex unlocked as destruction
138 * of the interpreter can lead to recursive destruction calls that could
139 * lead to a deadlock on that mutex.
142 S_ithread_clear(pTHX_ ithread *thread)
144 PerlInterpreter *interp;
146 assert(((thread->state & PERL_ITHR_FINISHED) &&
147 (thread->state & PERL_ITHR_UNCALLABLE))
149 (thread->state & PERL_ITHR_NONVIABLE));
151 interp = thread->interp;
155 PERL_SET_CONTEXT(interp);
156 S_ithread_set(aTHX_ thread);
158 SvREFCNT_dec(thread->params);
159 thread->params = Nullsv;
162 SvREFCNT_dec(thread->err);
163 thread->err = Nullsv;
166 perl_destruct(interp);
168 thread->interp = NULL;
171 PERL_SET_CONTEXT(aTHX);
175 /* Decrement the refcount of an ithread, and if it reaches zero, free it.
176 * Must be called with the mutex held.
177 * On return, mutex is released (or destroyed).
180 S_ithread_free(pTHX_ ithread *thread)
187 if (! (thread->state & PERL_ITHR_NONVIABLE)) {
188 assert(thread->count > 0);
189 if (--thread->count > 0) {
190 MUTEX_UNLOCK(&thread->mutex);
193 assert((thread->state & PERL_ITHR_FINISHED) &&
194 (thread->state & PERL_ITHR_UNCALLABLE));
196 MUTEX_UNLOCK(&thread->mutex);
198 /* Main thread (0) is immortal and should never get here */
199 assert(thread->tid != 0);
201 /* Remove from circular list of threads */
202 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
203 assert(thread->prev && thread->next);
204 thread->next->prev = thread->prev;
205 thread->prev->next = thread->next;
208 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
210 /* Thread is now disowned */
211 MUTEX_LOCK(&thread->mutex);
212 S_ithread_clear(aTHX_ thread);
215 handle = thread->handle;
216 thread->handle = NULL;
218 MUTEX_UNLOCK(&thread->mutex);
219 MUTEX_DESTROY(&thread->mutex);
227 PerlMemShared_free(thread);
229 /* total_threads >= 1 is used to veto cleanup by the main thread,
230 * should it happen to exit while other threads still exist.
231 * Decrement this as the very last thing in the thread's existence.
232 * Otherwise, MY_POOL and global state such as PL_op_mutex may get
233 * freed while we're still using it.
235 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
236 MY_POOL.total_threads--;
237 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
242 S_ithread_count_inc(pTHX_ ithread *thread)
244 MUTEX_LOCK(&thread->mutex);
246 MUTEX_UNLOCK(&thread->mutex);
250 /* Warn if exiting with any unjoined threads */
254 int veto_cleanup, warn;
257 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
258 veto_cleanup = (MY_POOL.total_threads > 0);
259 warn = (MY_POOL.running_threads || MY_POOL.joinable_threads);
260 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
263 if (ckWARN_d(WARN_THREADS)) {
264 Perl_warn(aTHX_ "Perl exited with active threads:\n\t%"
265 IVdf " running and unjoined\n\t%"
266 IVdf " finished and unjoined\n\t%"
267 IVdf " running and detached\n",
268 MY_POOL.running_threads,
269 MY_POOL.joinable_threads,
270 MY_POOL.detached_threads);
274 return (veto_cleanup);
278 /* Called from perl_destruct() in each thread. If it's the main thread,
279 * stop it from freeing everything if there are other threads still running.
282 Perl_ithread_hook(pTHX)
285 return ((aTHX == MY_POOL.main_thread.interp) ? S_exit_warning(aTHX) : 0);
289 /* MAGIC (in mg.h sense) hooks */
292 ithread_mg_get(pTHX_ SV *sv, MAGIC *mg)
294 ithread *thread = (ithread *)mg->mg_ptr;
295 SvIV_set(sv, PTR2IV(thread));
301 ithread_mg_free(pTHX_ SV *sv, MAGIC *mg)
303 ithread *thread = (ithread *)mg->mg_ptr;
304 MUTEX_LOCK(&thread->mutex);
305 S_ithread_free(aTHX_ thread); /* Releases MUTEX */
310 ithread_mg_dup(pTHX_ MAGIC *mg, CLONE_PARAMS *param)
312 S_ithread_count_inc(aTHX_ (ithread *)mg->mg_ptr);
316 MGVTBL ithread_vtbl = {
317 ithread_mg_get, /* get */
321 ithread_mg_free, /* free */
323 ithread_mg_dup /* dup */
327 /* Provided default, minimum and rational stack sizes */
329 S_good_stack_size(pTHX_ IV stack_size)
333 /* Use default stack size if no stack size specified */
335 return (MY_POOL.default_stack_size);
338 #ifdef PTHREAD_STACK_MIN
339 /* Can't use less than minimum */
340 if (stack_size < PTHREAD_STACK_MIN) {
341 if (ckWARN(WARN_THREADS)) {
342 Perl_warn(aTHX_ "Using minimum thread stack size of %" IVdf, (IV)PTHREAD_STACK_MIN);
344 return (PTHREAD_STACK_MIN);
348 /* Round up to page size boundary */
349 if (MY_POOL.page_size <= 0) {
350 #if defined(HAS_SYSCONF) && (defined(_SC_PAGESIZE) || defined(_SC_MMAP_PAGE_SIZE))
351 SETERRNO(0, SS_NORMAL);
353 MY_POOL.page_size = sysconf(_SC_PAGESIZE);
355 MY_POOL.page_size = sysconf(_SC_MMAP_PAGE_SIZE);
357 if ((long)MY_POOL.page_size < 0) {
359 SV * const error = get_sv("@", FALSE);
360 (void)SvUPGRADE(error, SVt_PV);
361 Perl_croak(aTHX_ "PANIC: sysconf: %s", SvPV_nolen(error));
363 Perl_croak(aTHX_ "PANIC: sysconf: pagesize unknown");
367 # ifdef HAS_GETPAGESIZE
368 MY_POOL.page_size = getpagesize();
370 # if defined(I_SYS_PARAM) && defined(PAGESIZE)
371 MY_POOL.page_size = PAGESIZE;
373 MY_POOL.page_size = 8192; /* A conservative default */
376 if (MY_POOL.page_size <= 0) {
377 Perl_croak(aTHX_ "PANIC: bad pagesize %" IVdf, (IV)MY_POOL.page_size);
381 stack_size = ((stack_size + (MY_POOL.page_size - 1)) / MY_POOL.page_size) * MY_POOL.page_size;
387 /* Starts executing the thread.
388 * Passed as the C level function to run in the new thread.
391 STATIC THREAD_RET_TYPE
392 S_ithread_run(LPVOID arg)
395 S_ithread_run(void * arg)
398 ithread *thread = (ithread *)arg;
401 int exit_app = 0; /* Thread terminated using 'exit' */
403 int died = 0; /* Thread terminated abnormally */
407 dTHXa(thread->interp);
411 /* Blocked until ->create() call finishes */
412 MUTEX_LOCK(&thread->mutex);
413 MUTEX_UNLOCK(&thread->mutex);
415 PERL_SET_CONTEXT(thread->interp);
416 S_ithread_set(aTHX_ thread);
418 PL_perl_destruct_level = 2;
421 AV *params = (AV *)SvRV(thread->params);
422 int len = (int)av_len(params)+1;
429 /* Put args on the stack */
431 for (ii=0; ii < len; ii++) {
432 XPUSHs(av_shift(params));
436 oldscope = PL_scopestack_ix;
439 /* Run the specified function */
440 len = (int)call_sv(thread->init_function, thread->gimme|G_EVAL);
441 } else if (jmp_rc == 2) {
444 exit_code = STATUS_CURRENT;
445 while (PL_scopestack_ix > oldscope) {
451 /* Remove args from stack and put back in params array */
453 for (ii=len-1; ii >= 0; ii--) {
456 av_store(params, ii, SvREFCNT_inc(sv));
463 /* Check for abnormal termination */
465 died = PERL_ITHR_DIED;
466 thread->err = newSVsv(ERRSV);
467 /* If ERRSV is an object, remember the classname and then
468 * rebless into 'main' so it will survive 'cloning'
470 if (sv_isobject(thread->err)) {
471 thread->err_class = HvNAME(SvSTASH(SvRV(thread->err)));
472 sv_bless(thread->err, gv_stashpv("main", 0));
475 if (ckWARN_d(WARN_THREADS)) {
476 oldscope = PL_scopestack_ix;
479 /* Warn that thread died */
480 Perl_warn(aTHX_ "Thread %" UVuf " terminated abnormally: %" SVf, thread->tid, ERRSV);
481 } else if (jmp_rc == 2) {
482 /* Warn handler exited */
484 exit_code = STATUS_CURRENT;
485 while (PL_scopestack_ix > oldscope) {
493 /* Release function ref */
494 SvREFCNT_dec(thread->init_function);
495 thread->init_function = Nullsv;
498 PerlIO_flush((PerlIO *)NULL);
500 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
501 MUTEX_LOCK(&thread->mutex);
502 /* Mark as finished */
503 thread->state |= (PERL_ITHR_FINISHED | died);
504 /* Clear exit flag if required */
505 if (thread->state & PERL_ITHR_THREAD_EXIT_ONLY) {
509 /* Adjust thread status counts */
510 if (thread->state & PERL_ITHR_DETACHED) {
511 MY_POOL.detached_threads--;
513 MY_POOL.running_threads--;
514 MY_POOL.joinable_threads++;
516 MUTEX_UNLOCK(&thread->mutex);
517 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
519 /* Exit application if required */
521 oldscope = PL_scopestack_ix;
524 /* Warn if there are unjoined threads */
525 S_exit_warning(aTHX);
526 } else if (jmp_rc == 2) {
527 /* Warn handler exited */
528 exit_code = STATUS_CURRENT;
529 while (PL_scopestack_ix > oldscope) {
538 /* At this point, the interpreter may have been freed, so call
539 * free in the the context of of the 'main' interpreter which
540 * can't have been freed due to the veto_cleanup mechanism.
542 aTHX = MY_POOL.main_thread.interp;
544 MUTEX_LOCK(&thread->mutex);
545 S_ithread_free(aTHX_ thread); /* Releases MUTEX */
555 /* Type conversion helper functions */
558 S_ithread_to_SV(pTHX_ SV *obj, ithread *thread, char *classname, bool inc)
564 S_ithread_count_inc(aTHX_ thread);
570 sv = newSVrv(obj, classname);
571 sv_setiv(sv, PTR2IV(thread));
572 mg = sv_magicext(sv, Nullsv, PERL_MAGIC_shared_scalar, &ithread_vtbl, (char *)thread, 0);
573 mg->mg_flags |= MGf_DUP;
580 S_SV_to_ithread(pTHX_ SV *sv)
582 /* Argument is a thread */
584 return (INT2PTR(ithread *, SvIV(SvRV(sv))));
586 /* Argument is classname, therefore return current thread */
587 return (S_ithread_get(aTHX));
592 * Called in context of parent thread.
593 * Called with MY_POOL.create_destruct_mutex locked. (Unlocked on error.)
597 pTHX_ SV *init_function,
604 ithread *current_thread = S_ithread_get(aTHX);
606 SV **tmps_tmp = PL_tmps_stack;
607 IV tmps_ix = PL_tmps_ix;
609 int rc_stack_size = 0;
610 int rc_thread_create = 0;
614 /* Allocate thread structure in context of the main thread's interpreter */
616 PERL_SET_CONTEXT(MY_POOL.main_thread.interp);
617 thread = (ithread *)PerlMemShared_malloc(sizeof(ithread));
619 PERL_SET_CONTEXT(aTHX);
621 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
622 PerlLIO_write(PerlIO_fileno(Perl_error_log), PL_no_mem, strlen(PL_no_mem));
625 Zero(thread, 1, ithread);
627 /* Add to threads list */
628 thread->next = &MY_POOL.main_thread;
629 thread->prev = MY_POOL.main_thread.prev;
630 MY_POOL.main_thread.prev = thread;
631 thread->prev->next = thread;
632 MY_POOL.total_threads++;
634 /* 1 ref to be held by the local var 'thread' in S_ithread_run().
635 * 1 ref to be held by the threads object that we assume we will
636 * be embedded in upon our return.
637 * 1 ref to be the responsibility of join/detach, so we don't get
638 * freed until join/detach, even if no thread objects remain.
639 * This allows the following to work:
640 * { threads->create(sub{...}); } threads->object(1)->join;
644 /* Block new thread until ->create() call finishes */
645 MUTEX_INIT(&thread->mutex);
646 MUTEX_LOCK(&thread->mutex);
648 thread->tid = MY_POOL.tid_counter++;
649 thread->stack_size = S_good_stack_size(aTHX_ stack_size);
650 thread->gimme = gimme;
651 thread->state = exit_opt;
653 /* "Clone" our interpreter into the thread's interpreter.
654 * This gives thread access to "static data" and code.
656 PerlIO_flush((PerlIO *)NULL);
657 S_ithread_set(aTHX_ thread);
659 SAVEBOOL(PL_srand_called); /* Save this so it becomes the correct value */
660 PL_srand_called = FALSE; /* Set it to false so we can detect if it gets
661 set during the clone */
664 thread->interp = perl_clone(aTHX, CLONEf_KEEP_PTR_TABLE | CLONEf_CLONE_HOST);
666 thread->interp = perl_clone(aTHX, CLONEf_KEEP_PTR_TABLE);
669 /* perl_clone() leaves us in new interpreter's context. As it is tricky
670 * to spot an implicit aTHX, create a new scope with aTHX matching the
671 * context for the duration of our work for new interpreter.
674 CLONE_PARAMS clone_param;
676 dTHXa(thread->interp);
680 /* Here we remove END blocks since they should only run in the thread
683 SvREFCNT_dec(PL_endav);
686 clone_param.flags = 0;
687 if (SvPOK(init_function)) {
688 thread->init_function = newSV(0);
689 sv_copypv(thread->init_function, init_function);
691 thread->init_function = sv_dup(init_function, &clone_param);
692 if (SvREFCNT(thread->init_function) == 0) {
693 SvREFCNT_inc_void(thread->init_function);
697 thread->params = sv_dup(params, &clone_param);
698 SvREFCNT_inc_void(thread->params);
700 /* The code below checks that anything living on the tmps stack and
701 * has been cloned (so it lives in the ptr_table) has a refcount
704 * If the refcount is 0 it means that a something on the stack/context
705 * was holding a reference to it and since we init_stacks() in
706 * perl_clone that won't get cleaned and we will get a leaked scalar.
707 * The reason it was cloned was that it lived on the @_ stack.
709 * Example of this can be found in bugreport 15837 where calls in the
710 * parameter list end up as a temp.
712 * One could argue that this fix should be in perl_clone.
714 while (tmps_ix > 0) {
715 SV* sv = (SV*)ptr_table_fetch(PL_ptr_table, tmps_tmp[tmps_ix]);
717 if (sv && SvREFCNT(sv) == 0) {
718 SvREFCNT_inc_void(sv);
723 SvTEMP_off(thread->init_function);
724 ptr_table_free(PL_ptr_table);
726 PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
728 S_ithread_set(aTHX_ current_thread);
729 PERL_SET_CONTEXT(aTHX);
731 /* Create/start the thread */
733 thread->handle = CreateThread(NULL,
734 (DWORD)thread->stack_size,
737 STACK_SIZE_PARAM_IS_A_RESERVATION,
741 STATIC pthread_attr_t attr;
742 STATIC int attr_inited = 0;
743 STATIC int attr_joinable = PTHREAD_CREATE_JOINABLE;
745 pthread_attr_init(&attr);
749 # ifdef PTHREAD_ATTR_SETDETACHSTATE
750 /* Threads start out joinable */
751 PTHREAD_ATTR_SETDETACHSTATE(&attr, attr_joinable);
754 # ifdef _POSIX_THREAD_ATTR_STACKSIZE
755 /* Set thread's stack size */
756 if (thread->stack_size > 0) {
757 rc_stack_size = pthread_attr_setstacksize(&attr, (size_t)thread->stack_size);
761 /* Create the thread */
762 if (! rc_stack_size) {
763 # ifdef OLD_PTHREADS_API
764 rc_thread_create = pthread_create(&thread->thr,
769 # if defined(HAS_PTHREAD_ATTR_SETSCOPE) && defined(PTHREAD_SCOPE_SYSTEM)
770 pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);
772 rc_thread_create = pthread_create(&thread->thr,
779 # ifdef _POSIX_THREAD_ATTR_STACKSIZE
780 /* Try to get thread's actual stack size */
784 stacksize = pthread_attr_getstacksize(attr);
786 if (! pthread_attr_getstacksize(&attr, &stacksize))
789 thread->stack_size = (IV)stacksize;
796 /* Check for errors */
798 if (thread->handle == NULL) {
800 if (rc_stack_size || rc_thread_create) {
802 /* Must unlock mutex for destruct call */
803 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
805 thread->state |= PERL_ITHR_NONVIABLE;
806 S_ithread_free(aTHX_ thread); /* Releases MUTEX */
808 if (ckWARN_d(WARN_THREADS)) {
810 Perl_warn(aTHX_ "Thread creation failed: pthread_attr_setstacksize(%" IVdf ") returned %d", thread->stack_size, rc_stack_size);
812 Perl_warn(aTHX_ "Thread creation failed: pthread_create returned %d", rc_thread_create);
819 MY_POOL.running_threads++;
824 #endif /* USE_ITHREADS */
827 MODULE = threads PACKAGE = threads PREFIX = ithread_
837 SV *function_to_call;
843 SV *thread_exit_only;
849 if ((items >= 2) && SvROK(ST(1)) && SvTYPE(SvRV(ST(1)))==SVt_PVHV) {
851 Perl_croak(aTHX_ "Usage: threads->create(\\%specs, function, ...)");
853 specs = (HV*)SvRV(ST(1));
857 Perl_croak(aTHX_ "Usage: threads->create(function, ...)");
863 if (sv_isobject(ST(0))) {
865 classname = HvNAME(SvSTASH(SvRV(ST(0))));
866 thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
867 MUTEX_LOCK(&thread->mutex);
868 stack_size = thread->stack_size;
869 exit_opt = thread->state & PERL_ITHR_THREAD_EXIT_ONLY;
870 MUTEX_UNLOCK(&thread->mutex);
872 /* threads->create() */
873 classname = (char *)SvPV_nolen(ST(0));
874 stack_size = MY_POOL.default_stack_size;
875 thread_exit_only = get_sv("threads::thread_exit_only", TRUE);
876 exit_opt = (SvTRUE(thread_exit_only))
877 ? PERL_ITHR_THREAD_EXIT_ONLY : 0;
880 function_to_call = ST(idx+1);
885 if (hv_exists(specs, "stack", 5)) {
886 stack_size = SvIV(*hv_fetch(specs, "stack", 5, 0));
887 } else if (hv_exists(specs, "stacksize", 9)) {
888 stack_size = SvIV(*hv_fetch(specs, "stacksize", 9, 0));
889 } else if (hv_exists(specs, "stack_size", 10)) {
890 stack_size = SvIV(*hv_fetch(specs, "stack_size", 10, 0));
894 if (hv_exists(specs, "context", 7)) {
895 str = (char *)SvPV_nolen(*hv_fetch(specs, "context", 7, 0));
910 Perl_croak(aTHX_ "Invalid context: %s", str);
912 } else if (hv_exists(specs, "array", 5)) {
913 if (SvTRUE(*hv_fetch(specs, "array", 5, 0))) {
916 } else if (hv_exists(specs, "scalar", 6)) {
917 if (SvTRUE(*hv_fetch(specs, "scalar", 6, 0))) {
920 } else if (hv_exists(specs, "void", 4)) {
921 if (SvTRUE(*hv_fetch(specs, "void", 4, 0))) {
926 /* exit => thread_only */
927 if (hv_exists(specs, "exit", 4)) {
928 str = (char *)SvPV_nolen(*hv_fetch(specs, "exit", 4, 0));
929 exit_opt = (*str == 't' || *str == 'T')
930 ? PERL_ITHR_THREAD_EXIT_ONLY : 0;
934 context = GIMME_V; /* Implicit context */
936 context |= (GIMME_V & (~(G_ARRAY|G_SCALAR|G_VOID)));
942 for (ii=2; ii < items ; ii++) {
943 av_push(params, SvREFCNT_inc(ST(idx+ii)));
948 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
949 thread = S_ithread_create(aTHX_ function_to_call,
953 newRV_noinc((SV*)params));
955 XSRETURN_UNDEF; /* Mutex already unlocked */
957 ST(0) = sv_2mortal(S_ithread_to_SV(aTHX_ Nullsv, thread, classname, FALSE));
958 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
961 MUTEX_UNLOCK(&thread->mutex);
963 /* XSRETURN(1); - implied */
973 int want_running = 0;
977 /* Class method only */
979 Perl_croak(aTHX_ "Usage: threads->list(...)");
981 classname = (char *)SvPV_nolen(ST(0));
983 /* Calling context */
984 list_context = (GIMME_V == G_ARRAY);
986 /* Running or joinable parameter */
988 want_running = SvTRUE(ST(1));
991 /* Walk through threads list */
992 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
993 for (thread = MY_POOL.main_thread.next;
994 thread != &MY_POOL.main_thread;
995 thread = thread->next)
997 MUTEX_LOCK(&thread->mutex);
998 state = thread->state;
999 MUTEX_UNLOCK(&thread->mutex);
1001 /* Ignore detached or joined threads */
1002 if (state & PERL_ITHR_UNCALLABLE) {
1006 /* Filter per parameter */
1009 if (state & PERL_ITHR_FINISHED) {
1010 continue; /* Not running */
1013 if (! (state & PERL_ITHR_FINISHED)) {
1014 continue; /* Still running - not joinable yet */
1019 /* Push object on stack if list context */
1021 XPUSHs(sv_2mortal(S_ithread_to_SV(aTHX_ Nullsv, thread, classname, TRUE)));
1025 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
1026 /* If scalar context, send back count */
1027 if (! list_context) {
1038 /* Class method only */
1039 if ((items != 1) || SvROK(ST(0))) {
1040 Perl_croak(aTHX_ "Usage: threads->self()");
1042 classname = (char *)SvPV_nolen(ST(0));
1044 thread = S_ithread_get(aTHX);
1046 ST(0) = sv_2mortal(S_ithread_to_SV(aTHX_ Nullsv, thread, classname, TRUE));
1047 /* XSRETURN(1); - implied */
1055 PERL_UNUSED_VAR(items);
1056 thread = S_SV_to_ithread(aTHX_ ST(0));
1057 XST_mUV(0, thread->tid);
1058 /* XSRETURN(1); - implied */
1065 ithread *current_thread;
1076 /* Object method only */
1077 if ((items != 1) || ! sv_isobject(ST(0))) {
1078 Perl_croak(aTHX_ "Usage: $thr->join()");
1081 /* Check if the thread is joinable and not ourselves */
1082 thread = S_SV_to_ithread(aTHX_ ST(0));
1083 current_thread = S_ithread_get(aTHX);
1085 MUTEX_LOCK(&thread->mutex);
1086 if ((join_err = (thread->state & PERL_ITHR_UNCALLABLE))) {
1087 MUTEX_UNLOCK(&thread->mutex);
1088 Perl_croak(aTHX_ (join_err & PERL_ITHR_DETACHED)
1089 ? "Cannot join a detached thread"
1090 : "Thread already joined");
1091 } else if (thread->tid == current_thread->tid) {
1092 MUTEX_UNLOCK(&thread->mutex);
1093 Perl_croak(aTHX_ "Cannot join self");
1096 /* Mark as joined */
1097 thread->state |= PERL_ITHR_JOINED;
1098 MUTEX_UNLOCK(&thread->mutex);
1100 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
1101 MY_POOL.joinable_threads--;
1102 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
1104 /* Join the thread */
1106 if (WaitForSingleObject(thread->handle, INFINITE) != WAIT_OBJECT_0) {
1107 /* Timeout/abandonment unexpected here; check $^E */
1108 Perl_croak(aTHX_ "PANIC: underlying join failed");
1111 if ((rc_join = pthread_join(thread->thr, &retval)) != 0) {
1112 /* In progress/deadlock/unknown unexpected here; check $! */
1114 Perl_croak(aTHX_ "PANIC: underlying join failed");
1118 MUTEX_LOCK(&thread->mutex);
1119 /* Get the return value from the call_sv */
1120 /* Objects do not survive this process - FIXME */
1121 if (! (thread->gimme & G_VOID)) {
1123 PerlInterpreter *other_perl;
1124 CLONE_PARAMS clone_params;
1126 params_copy = (AV *)SvRV(thread->params);
1127 other_perl = thread->interp;
1128 clone_params.stashes = newAV();
1129 clone_params.flags = CLONEf_JOIN_IN;
1130 PL_ptr_table = ptr_table_new();
1131 S_ithread_set(aTHX_ thread);
1132 /* Ensure 'meaningful' addresses retain their meaning */
1133 ptr_table_store(PL_ptr_table, &other_perl->Isv_undef, &PL_sv_undef);
1134 ptr_table_store(PL_ptr_table, &other_perl->Isv_no, &PL_sv_no);
1135 ptr_table_store(PL_ptr_table, &other_perl->Isv_yes, &PL_sv_yes);
1136 params = (AV *)sv_dup((SV*)params_copy, &clone_params);
1137 S_ithread_set(aTHX_ current_thread);
1138 SvREFCNT_dec(clone_params.stashes);
1139 SvREFCNT_inc_void(params);
1140 ptr_table_free(PL_ptr_table);
1141 PL_ptr_table = NULL;
1144 /* If thread didn't die, then we can free its interpreter */
1145 if (! (thread->state & PERL_ITHR_DIED)) {
1146 S_ithread_clear(aTHX_ thread);
1148 S_ithread_free(aTHX_ thread); /* Releases MUTEX */
1150 /* If no return values, then just return */
1155 /* Put return values on stack */
1156 len = (int)AvFILL(params);
1157 for (ii=0; ii <= len; ii++) {
1158 SV* param = av_shift(params);
1159 XPUSHs(sv_2mortal(param));
1162 /* Free return value array */
1163 SvREFCNT_dec(params);
1169 PERL_UNUSED_VAR(items);
1180 PERL_UNUSED_VAR(items);
1182 /* Detach the thread */
1183 thread = S_SV_to_ithread(aTHX_ ST(0));
1184 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
1185 MUTEX_LOCK(&thread->mutex);
1186 if (! (detach_err = (thread->state & PERL_ITHR_UNCALLABLE))) {
1187 /* Thread is detachable */
1188 thread->state |= PERL_ITHR_DETACHED;
1190 /* Windows has no 'detach thread' function */
1192 PERL_THREAD_DETACH(thread->thr);
1194 if (thread->state & PERL_ITHR_FINISHED) {
1195 MY_POOL.joinable_threads--;
1197 MY_POOL.running_threads--;
1198 MY_POOL.detached_threads++;
1201 MUTEX_UNLOCK(&thread->mutex);
1202 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
1205 Perl_croak(aTHX_ (detach_err & PERL_ITHR_DETACHED)
1206 ? "Thread already detached"
1207 : "Cannot detach a joined thread");
1210 /* If thread is finished and didn't die,
1211 * then we can free its interpreter */
1212 MUTEX_LOCK(&thread->mutex);
1213 if ((thread->state & PERL_ITHR_FINISHED) &&
1214 ! (thread->state & PERL_ITHR_DIED))
1216 S_ithread_clear(aTHX_ thread);
1218 S_ithread_free(aTHX_ thread); /* Releases MUTEX */
1228 /* Must have safe signals */
1229 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG) {
1230 Perl_croak(aTHX_ "Cannot signal threads without safe signals");
1233 /* Object method only */
1234 if ((items != 2) || ! sv_isobject(ST(0))) {
1235 Perl_croak(aTHX_ "Usage: $thr->kill('SIG...')");
1239 sig_name = SvPV_nolen(ST(1));
1240 if (isALPHA(*sig_name)) {
1241 if (*sig_name == 'S' && sig_name[1] == 'I' && sig_name[2] == 'G') {
1244 if ((signal = whichsig(sig_name)) < 0) {
1245 Perl_croak(aTHX_ "Unrecognized signal name: %s", sig_name);
1248 signal = SvIV(ST(1));
1251 /* Set the signal for the thread */
1252 thread = S_SV_to_ithread(aTHX_ ST(0));
1253 MUTEX_LOCK(&thread->mutex);
1254 if (thread->interp) {
1255 dTHXa(thread->interp);
1256 PL_psig_pend[signal]++;
1259 MUTEX_UNLOCK(&thread->mutex);
1261 /* Return the thread to allow for method chaining */
1263 /* XSRETURN(1); - implied */
1267 ithread_DESTROY(...)
1269 PERL_UNUSED_VAR(items);
1270 sv_unmagic(SvRV(ST(0)), PERL_MAGIC_shared_scalar);
1278 PERL_UNUSED_VAR(items);
1280 /* Compares TIDs to determine thread equality */
1281 if (sv_isobject(ST(0)) && sv_isobject(ST(1))) {
1282 ithread *thr1 = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1283 ithread *thr2 = INT2PTR(ithread *, SvIV(SvRV(ST(1))));
1284 are_equal = (thr1->tid == thr2->tid);
1289 /* Return 0 on false for backward compatibility */
1292 /* XSRETURN(1); - implied */
1305 /* Class method only */
1307 Perl_croak(aTHX_ "Usage: threads->object($tid)");
1309 classname = (char *)SvPV_nolen(ST(0));
1311 if ((items < 2) || ! SvOK(ST(1))) {
1315 /* threads->object($tid) */
1318 /* Walk through threads list */
1319 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
1320 for (thread = MY_POOL.main_thread.next;
1321 thread != &MY_POOL.main_thread;
1322 thread = thread->next)
1325 if (thread->tid == tid) {
1326 /* Ignore if detached or joined */
1327 MUTEX_LOCK(&thread->mutex);
1328 state = thread->state;
1329 MUTEX_UNLOCK(&thread->mutex);
1330 if (! (state & PERL_ITHR_UNCALLABLE)) {
1331 /* Put object on stack */
1332 ST(0) = sv_2mortal(S_ithread_to_SV(aTHX_ Nullsv, thread, classname, TRUE));
1338 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
1343 /* XSRETURN(1); - implied */
1347 ithread__handle(...);
1351 PERL_UNUSED_VAR(items);
1352 thread = S_SV_to_ithread(aTHX_ ST(0));
1354 XST_mUV(0, PTR2UV(&thread->handle));
1356 XST_mUV(0, PTR2UV(&thread->thr));
1358 /* XSRETURN(1); - implied */
1362 ithread_get_stack_size(...)
1367 PERL_UNUSED_VAR(items);
1368 if (sv_isobject(ST(0))) {
1369 /* $thr->get_stack_size() */
1370 ithread *thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1371 stack_size = thread->stack_size;
1373 /* threads->get_stack_size() */
1374 stack_size = MY_POOL.default_stack_size;
1376 XST_mIV(0, stack_size);
1377 /* XSRETURN(1); - implied */
1381 ithread_set_stack_size(...)
1387 Perl_croak(aTHX_ "Usage: threads->set_stack_size($size)");
1389 if (sv_isobject(ST(0))) {
1390 Perl_croak(aTHX_ "Cannot change stack size of an existing thread");
1392 if (! looks_like_number(ST(1))) {
1393 Perl_croak(aTHX_ "Stack size must be numeric");
1396 old_size = MY_POOL.default_stack_size;
1397 MY_POOL.default_stack_size = S_good_stack_size(aTHX_ SvIV(ST(1)));
1398 XST_mIV(0, old_size);
1399 /* XSRETURN(1); - implied */
1403 ithread_is_running(...)
1407 /* Object method only */
1408 if ((items != 1) || ! sv_isobject(ST(0))) {
1409 Perl_croak(aTHX_ "Usage: $thr->is_running()");
1412 thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1413 MUTEX_LOCK(&thread->mutex);
1414 ST(0) = (thread->state & PERL_ITHR_FINISHED) ? &PL_sv_no : &PL_sv_yes;
1415 MUTEX_UNLOCK(&thread->mutex);
1416 /* XSRETURN(1); - implied */
1420 ithread_is_detached(...)
1424 PERL_UNUSED_VAR(items);
1425 thread = S_SV_to_ithread(aTHX_ ST(0));
1426 MUTEX_LOCK(&thread->mutex);
1427 ST(0) = (thread->state & PERL_ITHR_DETACHED) ? &PL_sv_yes : &PL_sv_no;
1428 MUTEX_UNLOCK(&thread->mutex);
1429 /* XSRETURN(1); - implied */
1433 ithread_is_joinable(...)
1437 /* Object method only */
1438 if ((items != 1) || ! sv_isobject(ST(0))) {
1439 Perl_croak(aTHX_ "Usage: $thr->is_joinable()");
1442 thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1443 MUTEX_LOCK(&thread->mutex);
1444 ST(0) = ((thread->state & PERL_ITHR_FINISHED) &&
1445 ! (thread->state & PERL_ITHR_UNCALLABLE))
1446 ? &PL_sv_yes : &PL_sv_no;
1447 MUTEX_UNLOCK(&thread->mutex);
1448 /* XSRETURN(1); - implied */
1452 ithread_wantarray(...)
1456 PERL_UNUSED_VAR(items);
1457 thread = S_SV_to_ithread(aTHX_ ST(0));
1458 ST(0) = (thread->gimme & G_ARRAY) ? &PL_sv_yes :
1459 (thread->gimme & G_VOID) ? &PL_sv_undef
1460 /* G_SCALAR */ : &PL_sv_no;
1461 /* XSRETURN(1); - implied */
1465 ithread_set_thread_exit_only(...)
1470 Perl_croak(aTHX_ "Usage: ->set_thread_exit_only(boolean)");
1472 thread = S_SV_to_ithread(aTHX_ ST(0));
1473 MUTEX_LOCK(&thread->mutex);
1474 if (SvTRUE(ST(1))) {
1475 thread->state |= PERL_ITHR_THREAD_EXIT_ONLY;
1477 thread->state &= ~PERL_ITHR_THREAD_EXIT_ONLY;
1479 MUTEX_UNLOCK(&thread->mutex);
1488 /* Object method only */
1489 if ((items != 1) || ! sv_isobject(ST(0))) {
1490 Perl_croak(aTHX_ "Usage: $thr->err()");
1493 thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1494 MUTEX_LOCK(&thread->mutex);
1496 /* If thread died, then clone the error into the calling thread */
1497 if (thread->state & PERL_ITHR_DIED) {
1498 PerlInterpreter *other_perl;
1499 CLONE_PARAMS clone_params;
1500 ithread *current_thread;
1502 other_perl = thread->interp;
1503 clone_params.stashes = newAV();
1504 clone_params.flags = CLONEf_JOIN_IN;
1505 PL_ptr_table = ptr_table_new();
1506 current_thread = S_ithread_get(aTHX);
1507 S_ithread_set(aTHX_ thread);
1508 /* Ensure 'meaningful' addresses retain their meaning */
1509 ptr_table_store(PL_ptr_table, &other_perl->Isv_undef, &PL_sv_undef);
1510 ptr_table_store(PL_ptr_table, &other_perl->Isv_no, &PL_sv_no);
1511 ptr_table_store(PL_ptr_table, &other_perl->Isv_yes, &PL_sv_yes);
1512 err = sv_dup(thread->err, &clone_params);
1513 S_ithread_set(aTHX_ current_thread);
1514 SvREFCNT_dec(clone_params.stashes);
1515 SvREFCNT_inc_void(err);
1516 /* If error was an object, bless it into the correct class */
1517 if (thread->err_class) {
1518 sv_bless(err, gv_stashpv(thread->err_class, 1));
1520 ptr_table_free(PL_ptr_table);
1521 PL_ptr_table = NULL;
1524 MUTEX_UNLOCK(&thread->mutex);
1530 ST(0) = sv_2mortal(err);
1531 /* XSRETURN(1); - implied */
1534 #endif /* USE_ITHREADS */
1540 SV *my_pool_sv = *hv_fetch(PL_modglobal, MY_POOL_KEY,
1541 sizeof(MY_POOL_KEY)-1, TRUE);
1542 my_pool_t *my_poolp = (my_pool_t*)SvPVX(newSV(sizeof(my_pool_t)-1));
1546 Zero(my_poolp, 1, my_pool_t);
1547 sv_setuv(my_pool_sv, PTR2UV(my_poolp));
1549 PL_perl_destruct_level = 2;
1550 MUTEX_INIT(&MY_POOL.create_destruct_mutex);
1551 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
1553 PL_threadhook = &Perl_ithread_hook;
1555 MY_POOL.tid_counter = 1;
1556 # ifdef THREAD_CREATE_NEEDS_STACK
1557 MY_POOL.default_stack_size = THREAD_CREATE_NEEDS_STACK;
1560 /* The 'main' thread is thread 0.
1561 * It is detached (unjoinable) and immortal.
1564 MUTEX_INIT(&MY_POOL.main_thread.mutex);
1566 /* Head of the threads list */
1567 MY_POOL.main_thread.next = &MY_POOL.main_thread;
1568 MY_POOL.main_thread.prev = &MY_POOL.main_thread;
1570 MY_POOL.main_thread.count = 1; /* Immortal */
1572 MY_POOL.main_thread.interp = aTHX;
1573 MY_POOL.main_thread.state = PERL_ITHR_DETACHED; /* Detached */
1574 MY_POOL.main_thread.stack_size = MY_POOL.default_stack_size;
1576 MY_POOL.main_thread.thr = GetCurrentThreadId();
1578 MY_POOL.main_thread.thr = pthread_self();
1581 S_ithread_set(aTHX_ &MY_POOL.main_thread);
1582 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
1583 #endif /* USE_ITHREADS */