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
53 typedef struct _ithread {
54 struct _ithread *next; /* Next thread in the list */
55 struct _ithread *prev; /* Prev thread in the list */
56 PerlInterpreter *interp; /* The threads interpreter */
57 UV tid; /* Threads module's thread id */
58 perl_mutex mutex; /* Mutex for updating things in this struct */
59 int count; /* How many SVs have a reference to us */
60 int state; /* Detached, joined, finished, etc. */
61 int gimme; /* Context of create */
62 SV *init_function; /* Code to run */
63 SV *params; /* Args to pass function */
65 DWORD thr; /* OS's idea if thread id */
66 HANDLE handle; /* OS's waitable handle */
68 pthread_t thr; /* OS's handle for the thread */
74 /* Used by Perl interpreter for thread context switching */
75 #define MY_CXT_KEY "threads::_guts" XS_VERSION
84 /* Linked list of all threads */
85 static ithread *threads;
87 /* Protects the creation and destruction of threads*/
88 static perl_mutex create_destruct_mutex;
90 static UV tid_counter = 0;
91 static IV joinable_threads = 0;
92 static IV running_threads = 0;
93 static IV detached_threads = 0;
94 #ifdef THREAD_CREATE_NEEDS_STACK
95 static IV default_stack_size = THREAD_CREATE_NEEDS_STACK;
97 static IV default_stack_size = 0;
99 static IV page_size = 0;
102 /* Used by Perl interpreter for thread context switching */
104 S_ithread_set(pTHX_ ithread *thread)
107 MY_CXT.thread = thread;
114 return (MY_CXT.thread);
118 /* Free any data (such as the Perl interpreter) attached to an ithread
119 * structure. This is a bit like undef on SVs, where the SV isn't freed,
120 * but the PVX is. Must be called with thread->mutex already held.
123 S_ithread_clear(pTHX_ ithread *thread)
125 PerlInterpreter *interp;
127 assert((thread->state & PERL_ITHR_FINISHED) &&
128 (thread->state & (PERL_ITHR_DETACHED|PERL_ITHR_JOINED)));
130 interp = thread->interp;
134 PERL_SET_CONTEXT(interp);
135 S_ithread_set(aTHX_ thread);
137 SvREFCNT_dec(thread->params);
138 thread->params = Nullsv;
140 perl_destruct(interp);
141 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)
158 MUTEX_LOCK(&thread->mutex);
160 /* Thread is still in use */
161 if (thread->count != 0) {
162 MUTEX_UNLOCK(&thread->mutex);
166 /* Main thread (0) is immortal and should never get here */
167 assert(thread->tid != 0);
169 /* Remove from circular list of threads */
170 MUTEX_LOCK(&create_destruct_mutex);
171 thread->next->prev = thread->prev;
172 thread->prev->next = thread->next;
175 MUTEX_UNLOCK(&create_destruct_mutex);
177 /* Thread is now disowned */
178 S_ithread_clear(aTHX_ thread);
181 handle = thread->handle;
182 thread->handle = NULL;
184 MUTEX_UNLOCK(&thread->mutex);
185 MUTEX_DESTROY(&thread->mutex);
192 /* Call PerlMemShared_free() in the context of the "first" interpreter
193 * per http://www.nntp.perl.org/group/perl.perl5.porters/110772
196 PerlMemShared_free(thread);
202 Perl_ithread_hook(pTHX)
204 int veto_cleanup = 0;
205 MUTEX_LOCK(&create_destruct_mutex);
206 if ((aTHX == PL_curinterp) &&
207 (running_threads || joinable_threads))
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 MUTEX_UNLOCK(&create_destruct_mutex);
221 return (veto_cleanup);
225 /* MAGIC (in mg.h sense) hooks */
228 ithread_mg_get(pTHX_ SV *sv, MAGIC *mg)
230 ithread *thread = (ithread *)mg->mg_ptr;
231 SvIV_set(sv, PTR2IV(thread));
237 ithread_mg_free(pTHX_ SV *sv, MAGIC *mg)
239 ithread *thread = (ithread *)mg->mg_ptr;
242 MUTEX_LOCK(&thread->mutex);
243 cleanup = ((--thread->count == 0) &&
244 (thread->state & PERL_ITHR_FINISHED) &&
245 (thread->state & (PERL_ITHR_DETACHED|PERL_ITHR_JOINED)));
246 MUTEX_UNLOCK(&thread->mutex);
249 S_ithread_destruct(aTHX_ thread);
254 ithread_mg_dup(pTHX_ MAGIC *mg, CLONE_PARAMS *param)
256 ithread *thread = (ithread *)mg->mg_ptr;
257 MUTEX_LOCK(&thread->mutex);
259 MUTEX_UNLOCK(&thread->mutex);
263 MGVTBL ithread_vtbl = {
264 ithread_mg_get, /* get */
268 ithread_mg_free, /* free */
270 ithread_mg_dup /* dup */
274 /* Provided default, minimum and rational stack sizes */
276 good_stack_size(pTHX_ IV stack_size)
278 /* Use default stack size if no stack size specified */
280 return (default_stack_size);
282 #ifdef PTHREAD_STACK_MIN
283 /* Can't use less than minimum */
284 if (stack_size < PTHREAD_STACK_MIN) {
285 if (ckWARN(WARN_THREADS)) {
286 Perl_warn(aTHX_ "Using minimum thread stack size of %" IVdf, (IV)PTHREAD_STACK_MIN);
288 return (PTHREAD_STACK_MIN);
292 /* Round up to page size boundary */
293 if (page_size <= 0) {
294 #if defined(HAS_SYSCONF) && (defined(_SC_PAGESIZE) || defined(_SC_MMAP_PAGE_SIZE))
295 SETERRNO(0, SS_NORMAL);
297 page_size = sysconf(_SC_PAGESIZE);
299 page_size = sysconf(_SC_MMAP_PAGE_SIZE);
301 if ((long)page_size < 0) {
303 SV * const error = get_sv("@", FALSE);
304 (void)SvUPGRADE(error, SVt_PV);
305 Perl_croak(aTHX_ "PANIC: sysconf: %s", SvPV_nolen(error));
307 Perl_croak(aTHX_ "PANIC: sysconf: pagesize unknown");
311 # ifdef HAS_GETPAGESIZE
312 page_size = getpagesize();
314 # if defined(I_SYS_PARAM) && defined(PAGESIZE)
315 page_size = PAGESIZE;
317 page_size = 8192; /* A conservative default */
321 Perl_croak(aTHX_ "PANIC: bad pagesize %" IVdf, (IV)page_size);
324 stack_size = ((stack_size + (page_size - 1)) / page_size) * page_size;
330 /* Starts executing the thread.
331 * Passed as the C level function to run in the new thread.
334 static THREAD_RET_TYPE
335 S_ithread_run(LPVOID arg)
338 S_ithread_run(void * arg)
341 ithread *thread = (ithread *)arg;
344 dTHXa(thread->interp);
345 PERL_SET_CONTEXT(thread->interp);
346 S_ithread_set(aTHX_ thread);
349 /* Far from clear messing with ->thr child-side is a good idea */
350 MUTEX_LOCK(&thread->mutex);
352 thread->thr = GetCurrentThreadId();
354 thread->thr = pthread_self();
356 MUTEX_UNLOCK(&thread->mutex);
359 PL_perl_destruct_level = 2;
362 AV *params = (AV *)SvRV(thread->params);
363 int len = (int)av_len(params)+1;
374 /* Put args on the stack */
376 for (ii=0; ii < len; ii++) {
377 XPUSHs(av_shift(params));
381 oldscope = PL_scopestack_ix;
384 /* Run the specified function */
385 len = (int)call_sv(thread->init_function, thread->gimme|G_EVAL);
386 } else if (jmp_rc == 2) {
387 while (PL_scopestack_ix > oldscope) {
393 /* Remove args from stack and put back in params array */
395 for (ii=len-1; ii >= 0; ii--) {
398 av_store(params, ii, SvREFCNT_inc(sv));
405 /* Check for failure */
406 if (SvTRUE(ERRSV) && ckWARN_d(WARN_THREADS)) {
407 oldscope = PL_scopestack_ix;
410 Perl_warn(aTHX_ "Thread %" UVuf " terminated abnormally: %" SVf, thread->tid, ERRSV);
411 } else if (jmp_rc == 2) {
412 while (PL_scopestack_ix > oldscope) {
419 /* Release function ref */
420 SvREFCNT_dec(thread->init_function);
421 thread->init_function = Nullsv;
424 PerlIO_flush((PerlIO *)NULL);
426 MUTEX_LOCK(&thread->mutex);
427 /* Mark as finished */
428 thread->state |= PERL_ITHR_FINISHED;
429 /* Cleanup if detached */
430 cleanup = (thread->state & PERL_ITHR_DETACHED);
431 MUTEX_UNLOCK(&thread->mutex);
434 MUTEX_LOCK(&create_destruct_mutex);
436 MUTEX_UNLOCK(&create_destruct_mutex);
437 S_ithread_destruct(aTHX_ thread);
439 MUTEX_LOCK(&create_destruct_mutex);
442 MUTEX_UNLOCK(&create_destruct_mutex);
453 /* Type conversion helper functions */
455 ithread_to_SV(pTHX_ SV *obj, ithread *thread, char *classname, bool inc)
461 MUTEX_LOCK(&thread->mutex);
463 MUTEX_UNLOCK(&thread->mutex);
470 sv = newSVrv(obj, classname);
471 sv_setiv(sv, PTR2IV(thread));
472 mg = sv_magicext(sv, Nullsv, PERL_MAGIC_shared_scalar, &ithread_vtbl, (char *)thread, 0);
473 mg->mg_flags |= MGf_DUP;
480 SV_to_ithread(pTHX_ SV *sv)
482 /* Argument is a thread */
484 return (INT2PTR(ithread *, SvIV(SvRV(sv))));
486 /* Argument is classname, therefore return current thread */
487 return (S_ithread_get(aTHX));
492 * Called in context of parent thread.
504 CLONE_PARAMS clone_param;
505 ithread *current_thread = S_ithread_get(aTHX);
507 SV **tmps_tmp = PL_tmps_stack;
508 IV tmps_ix = PL_tmps_ix;
510 int rc_stack_size = 0;
511 int rc_thread_create = 0;
514 MUTEX_LOCK(&create_destruct_mutex);
516 /* Allocate thread structure */
517 thread = (ithread *)PerlMemShared_malloc(sizeof(ithread));
519 MUTEX_UNLOCK(&create_destruct_mutex);
520 PerlLIO_write(PerlIO_fileno(Perl_error_log), PL_no_mem, strlen(PL_no_mem));
523 Zero(thread, 1, ithread);
525 /* Add to threads list */
526 thread->next = threads;
527 thread->prev = threads->prev;
528 threads->prev = thread;
529 thread->prev->next = thread;
531 /* Set count to 1 immediately in case thread exits before
532 * we return to caller!
536 MUTEX_INIT(&thread->mutex);
537 thread->tid = tid_counter++;
538 thread->stack_size = good_stack_size(aTHX_ stack_size);
539 thread->gimme = gimme;
541 /* "Clone" our interpreter into the thread's interpreter.
542 * This gives thread access to "static data" and code.
544 PerlIO_flush((PerlIO *)NULL);
545 S_ithread_set(aTHX_ thread);
547 SAVEBOOL(PL_srand_called); /* Save this so it becomes the correct value */
548 PL_srand_called = FALSE; /* Set it to false so we can detect if it gets
549 set during the clone */
552 thread->interp = perl_clone(aTHX, CLONEf_KEEP_PTR_TABLE | CLONEf_CLONE_HOST);
554 thread->interp = perl_clone(aTHX, CLONEf_KEEP_PTR_TABLE);
557 /* perl_clone() leaves us in new interpreter's context. As it is tricky
558 * to spot an implicit aTHX, create a new scope with aTHX matching the
559 * context for the duration of our work for new interpreter.
562 dTHXa(thread->interp);
566 /* Here we remove END blocks since they should only run in the thread
569 SvREFCNT_dec(PL_endav);
572 if (SvPOK(init_function)) {
573 thread->init_function = newSV(0);
574 sv_copypv(thread->init_function, init_function);
576 clone_param.flags = 0;
577 thread->init_function = sv_dup(init_function, &clone_param);
578 if (SvREFCNT(thread->init_function) == 0) {
579 SvREFCNT_inc(thread->init_function);
583 thread->params = sv_dup(params, &clone_param);
584 SvREFCNT_inc(thread->params);
586 /* The code below checks that anything living on the tmps stack and
587 * has been cloned (so it lives in the ptr_table) has a refcount
590 * If the refcount is 0 it means that a something on the stack/context
591 * was holding a reference to it and since we init_stacks() in
592 * perl_clone that won't get cleaned and we will get a leaked scalar.
593 * The reason it was cloned was that it lived on the @_ stack.
595 * Example of this can be found in bugreport 15837 where calls in the
596 * parameter list end up as a temp.
598 * One could argue that this fix should be in perl_clone.
600 while (tmps_ix > 0) {
601 SV* sv = (SV*)ptr_table_fetch(PL_ptr_table, tmps_tmp[tmps_ix]);
603 if (sv && SvREFCNT(sv) == 0) {
609 SvTEMP_off(thread->init_function);
610 ptr_table_free(PL_ptr_table);
612 PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
614 S_ithread_set(aTHX_ current_thread);
615 PERL_SET_CONTEXT(aTHX);
617 /* Create/start the thread */
619 thread->handle = CreateThread(NULL,
620 (DWORD)thread->stack_size,
623 STACK_SIZE_PARAM_IS_A_RESERVATION,
627 static pthread_attr_t attr;
628 static int attr_inited = 0;
629 static int attr_joinable = PTHREAD_CREATE_JOINABLE;
631 pthread_attr_init(&attr);
635 # ifdef PTHREAD_ATTR_SETDETACHSTATE
636 /* Threads start out joinable */
637 PTHREAD_ATTR_SETDETACHSTATE(&attr, attr_joinable);
640 # ifdef _POSIX_THREAD_ATTR_STACKSIZE
641 /* Set thread's stack size */
642 if (thread->stack_size > 0) {
643 rc_stack_size = pthread_attr_setstacksize(&attr, (size_t)thread->stack_size);
647 /* Create the thread */
648 if (! rc_stack_size) {
649 # ifdef OLD_PTHREADS_API
650 rc_thread_create = pthread_create(&thread->thr,
655 # if defined(HAS_PTHREAD_ATTR_SETSCOPE) && defined(PTHREAD_SCOPE_SYSTEM)
656 pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);
658 rc_thread_create = pthread_create(&thread->thr,
665 # ifdef _POSIX_THREAD_ATTR_STACKSIZE
666 /* Try to get thread's actual stack size */
670 stacksize = pthread_attr_getstacksize(attr);
672 if (! pthread_attr_getstacksize(&attr, &stacksize))
675 thread->stack_size = (IV)stacksize;
682 /* Check for errors */
684 if (thread->handle == NULL) {
686 if (rc_stack_size || rc_thread_create) {
688 MUTEX_UNLOCK(&create_destruct_mutex);
690 S_ithread_destruct(aTHX_ thread);
692 if (ckWARN_d(WARN_THREADS)) {
694 Perl_warn(aTHX_ "Thread creation failed: pthread_attr_setstacksize(%" IVdf ") returned %d", thread->stack_size, rc_stack_size);
696 Perl_warn(aTHX_ "Thread creation failed: pthread_create returned %d", rc_thread_create);
699 return (&PL_sv_undef);
703 MUTEX_UNLOCK(&create_destruct_mutex);
707 return (ithread_to_SV(aTHX_ obj, thread, classname, FALSE));
710 #endif /* USE_ITHREADS */
713 MODULE = threads PACKAGE = threads PREFIX = ithread_
723 SV *function_to_call;
732 if ((items >= 2) && SvROK(ST(1)) && SvTYPE(SvRV(ST(1)))==SVt_PVHV) {
734 Perl_croak(aTHX_ "Usage: threads->create(\\%specs, function, ...)");
735 specs = (HV*)SvRV(ST(1));
739 Perl_croak(aTHX_ "Usage: threads->create(function, ...)");
744 if (sv_isobject(ST(0))) {
746 classname = HvNAME(SvSTASH(SvRV(ST(0))));
747 thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
748 stack_size = thread->stack_size;
750 /* threads->create() */
751 classname = (char *)SvPV_nolen(ST(0));
752 stack_size = default_stack_size;
755 function_to_call = ST(idx+1);
760 if (hv_exists(specs, "stack", 5)) {
761 stack_size = SvIV(*hv_fetch(specs, "stack", 5, 0));
762 } else if (hv_exists(specs, "stacksize", 9)) {
763 stack_size = SvIV(*hv_fetch(specs, "stacksize", 9, 0));
764 } else if (hv_exists(specs, "stack_size", 10)) {
765 stack_size = SvIV(*hv_fetch(specs, "stack_size", 10, 0));
769 if (hv_exists(specs, "context", 7)) {
770 str = (char *)SvPV_nolen(*hv_fetch(specs, "context", 7, 0));
785 Perl_croak(aTHX_ "Invalid context: %s", str);
787 } else if (hv_exists(specs, "array", 5)) {
788 if (SvTRUE(*hv_fetch(specs, "array", 5, 0))) {
791 } else if (hv_exists(specs, "scalar", 6)) {
792 if (SvTRUE(*hv_fetch(specs, "scalar", 6, 0))) {
795 } else if (hv_exists(specs, "void", 4)) {
796 if (SvTRUE(*hv_fetch(specs, "void", 4, 0))) {
802 context = GIMME_V; /* Implicit context */
804 context |= (GIMME_V & (~(G_ARRAY|G_SCALAR|G_VOID)));
810 for (ii=2; ii < items ; ii++) {
811 av_push(params, SvREFCNT_inc(ST(idx+ii)));
816 ST(0) = sv_2mortal(S_ithread_create(aTHX_ Nullsv,
821 newRV_noinc((SV*)params)));
822 /* XSRETURN(1); - implied */
834 /* Class method only */
836 Perl_croak(aTHX_ "Usage: threads->list(...)");
837 classname = (char *)SvPV_nolen(ST(0));
839 /* Calling context */
840 list_context = (GIMME_V == G_ARRAY);
842 /* Running or joinable parameter */
844 want_running = SvTRUE(ST(1));
847 /* Walk through threads list */
848 MUTEX_LOCK(&create_destruct_mutex);
849 for (thread = threads->next;
851 thread = thread->next)
853 /* Ignore detached or joined threads */
854 if (thread->state & (PERL_ITHR_DETACHED|PERL_ITHR_JOINED)) {
858 /* Filter per parameter */
861 if (thread->state & PERL_ITHR_FINISHED) {
862 continue; /* Not running */
865 if (! (thread->state & PERL_ITHR_FINISHED)) {
866 continue; /* Still running - not joinable yet */
871 /* Push object on stack if list context */
873 XPUSHs(sv_2mortal(ithread_to_SV(aTHX_ Nullsv, thread, classname, TRUE)));
877 MUTEX_UNLOCK(&create_destruct_mutex);
878 /* If scalar context, send back count */
879 if (! list_context) {
890 /* Class method only */
892 Perl_croak(aTHX_ "Usage: threads->self()");
893 classname = (char *)SvPV_nolen(ST(0));
895 thread = S_ithread_get(aTHX);
897 ST(0) = sv_2mortal(ithread_to_SV(aTHX_ Nullsv, thread, classname, TRUE));
898 /* XSRETURN(1); - implied */
906 thread = SV_to_ithread(aTHX_ ST(0));
907 XST_mUV(0, thread->tid);
908 /* XSRETURN(1); - implied */
925 /* Object method only */
926 if (! sv_isobject(ST(0)))
927 Perl_croak(aTHX_ "Usage: $thr->join()");
929 /* Check if the thread is joinable */
930 thread = SV_to_ithread(aTHX_ ST(0));
931 MUTEX_LOCK(&thread->mutex);
932 join_err = (thread->state & (PERL_ITHR_DETACHED|PERL_ITHR_JOINED));
933 MUTEX_UNLOCK(&thread->mutex);
935 if (join_err & PERL_ITHR_DETACHED) {
936 Perl_croak(aTHX_ "Cannot join a detached thread");
938 Perl_croak(aTHX_ "Thread already joined");
942 /* Join the thread */
944 waitcode = WaitForSingleObject(thread->handle, INFINITE);
946 pthread_join(thread->thr, &retval);
949 MUTEX_LOCK(&thread->mutex);
951 thread->state |= PERL_ITHR_JOINED;
953 /* Get the return value from the call_sv */
956 PerlInterpreter *other_perl;
957 CLONE_PARAMS clone_params;
958 ithread *current_thread;
960 params_copy = (AV *)SvRV(thread->params);
961 other_perl = thread->interp;
962 clone_params.stashes = newAV();
963 clone_params.flags = CLONEf_JOIN_IN;
964 PL_ptr_table = ptr_table_new();
965 current_thread = S_ithread_get(aTHX);
966 S_ithread_set(aTHX_ thread);
967 /* Ensure 'meaningful' addresses retain their meaning */
968 ptr_table_store(PL_ptr_table, &other_perl->Isv_undef, &PL_sv_undef);
969 ptr_table_store(PL_ptr_table, &other_perl->Isv_no, &PL_sv_no);
970 ptr_table_store(PL_ptr_table, &other_perl->Isv_yes, &PL_sv_yes);
971 params = (AV *)sv_dup((SV*)params_copy, &clone_params);
972 S_ithread_set(aTHX_ current_thread);
973 SvREFCNT_dec(clone_params.stashes);
974 SvREFCNT_inc(params);
975 ptr_table_free(PL_ptr_table);
979 /* We are finished with the thread */
980 S_ithread_clear(aTHX_ thread);
981 MUTEX_UNLOCK(&thread->mutex);
983 MUTEX_LOCK(&create_destruct_mutex);
985 MUTEX_UNLOCK(&create_destruct_mutex);
987 /* If no return values, then just return */
992 /* Put return values on stack */
993 len = (int)AvFILL(params);
994 for (ii=0; ii <= len; ii++) {
995 SV* param = av_shift(params);
996 XPUSHs(sv_2mortal(param));
999 /* Free return value array */
1000 SvREFCNT_dec(params);
1016 thread = SV_to_ithread(aTHX_ ST(0));
1017 MUTEX_LOCK(&thread->mutex);
1019 /* Check if the thread is detachable */
1020 if ((detach_err = (thread->state & (PERL_ITHR_DETACHED|PERL_ITHR_JOINED)))) {
1021 MUTEX_UNLOCK(&thread->mutex);
1022 if (detach_err & PERL_ITHR_DETACHED) {
1023 Perl_croak(aTHX_ "Thread already detached");
1025 Perl_croak(aTHX_ "Cannot detach a joined thread");
1029 /* Detach the thread */
1030 thread->state |= PERL_ITHR_DETACHED;
1032 /* Windows has no 'detach thread' function */
1034 PERL_THREAD_DETACH(thread->thr);
1036 /* Cleanup if finished */
1037 cleanup = (thread->state & PERL_ITHR_FINISHED);
1038 MUTEX_UNLOCK(&thread->mutex);
1040 MUTEX_LOCK(&create_destruct_mutex);
1047 MUTEX_UNLOCK(&create_destruct_mutex);
1050 S_ithread_destruct(aTHX_ thread);
1061 /* Must have safe signals */
1062 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
1063 Perl_croak(aTHX_ "Cannot signal threads without safe signals");
1065 /* Object method only */
1066 if (! sv_isobject(ST(0)))
1067 Perl_croak(aTHX_ "Usage: $thr->kill('SIG...')");
1070 sig_name = SvPV_nolen(ST(1));
1071 if (isALPHA(*sig_name)) {
1072 if (*sig_name == 'S' && sig_name[1] == 'I' && sig_name[2] == 'G')
1074 if ((signal = whichsig(sig_name)) < 0)
1075 Perl_croak(aTHX_ "Unrecognized signal name: %s", sig_name);
1077 signal = SvIV(ST(1));
1079 /* Set the signal for the thread */
1080 thread = SV_to_ithread(aTHX_ ST(0));
1081 MUTEX_LOCK(&thread->mutex);
1082 if (thread->interp) {
1083 dTHXa(thread->interp);
1084 PL_psig_pend[signal]++;
1087 MUTEX_UNLOCK(&thread->mutex);
1089 /* Return the thread to allow for method chaining */
1091 /* XSRETURN(1); - implied */
1095 ithread_DESTROY(...)
1097 sv_unmagic(SvRV(ST(0)), PERL_MAGIC_shared_scalar);
1105 /* Compares TIDs to determine thread equality */
1106 if (sv_isobject(ST(0)) && sv_isobject(ST(1))) {
1107 ithread *thr1 = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1108 ithread *thr2 = INT2PTR(ithread *, SvIV(SvRV(ST(1))));
1109 are_equal = (thr1->tid == thr2->tid);
1114 /* Return 0 on false for backward compatibility */
1117 /* XSRETURN(1); - implied */
1128 /* Class method only */
1130 Perl_croak(aTHX_ "Usage: threads->object($tid)");
1131 classname = (char *)SvPV_nolen(ST(0));
1133 if ((items < 2) || ! SvOK(ST(1))) {
1137 /* threads->object($tid) */
1140 /* Walk through threads list */
1141 MUTEX_LOCK(&create_destruct_mutex);
1142 for (thread = threads->next;
1144 thread = thread->next)
1146 /* Look for TID, but ignore detached or joined threads */
1147 if ((thread->tid != tid) ||
1148 (thread->state & (PERL_ITHR_DETACHED|PERL_ITHR_JOINED)))
1152 /* Put object on stack */
1153 ST(0) = sv_2mortal(ithread_to_SV(aTHX_ Nullsv, thread, classname, TRUE));
1157 MUTEX_UNLOCK(&create_destruct_mutex);
1161 /* XSRETURN(1); - implied */
1165 ithread__handle(...);
1169 thread = SV_to_ithread(aTHX_ ST(0));
1171 XST_mUV(0, PTR2UV(&thread->handle));
1173 XST_mUV(0, PTR2UV(&thread->thr));
1175 /* XSRETURN(1); - implied */
1179 ithread_get_stack_size(...)
1183 if (sv_isobject(ST(0))) {
1184 /* $thr->get_stack_size() */
1185 ithread *thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1186 stack_size = thread->stack_size;
1188 /* threads->get_stack_size() */
1189 stack_size = default_stack_size;
1191 XST_mIV(0, stack_size);
1192 /* XSRETURN(1); - implied */
1196 ithread_set_stack_size(...)
1201 Perl_croak(aTHX_ "Usage: threads->set_stack_size($size)");
1202 if (sv_isobject(ST(0)))
1203 Perl_croak(aTHX_ "Cannot change stack size of an existing thread");
1205 old_size = default_stack_size;
1206 default_stack_size = good_stack_size(aTHX_ SvIV(ST(1)));
1207 XST_mIV(0, old_size);
1208 /* XSRETURN(1); - implied */
1212 ithread_is_running(...)
1216 /* Object method only */
1217 if (! sv_isobject(ST(0)))
1218 Perl_croak(aTHX_ "Usage: $thr->is_running()");
1220 thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1221 MUTEX_LOCK(&thread->mutex);
1222 ST(0) = (thread->state & PERL_ITHR_FINISHED) ? &PL_sv_no : &PL_sv_yes;
1223 MUTEX_UNLOCK(&thread->mutex);
1224 /* XSRETURN(1); - implied */
1228 ithread_is_detached(...)
1232 thread = SV_to_ithread(aTHX_ ST(0));
1233 MUTEX_LOCK(&thread->mutex);
1234 ST(0) = (thread->state & PERL_ITHR_DETACHED) ? &PL_sv_yes : &PL_sv_no;
1235 MUTEX_UNLOCK(&thread->mutex);
1236 /* XSRETURN(1); - implied */
1240 ithread_is_joinable(...)
1244 /* Object method only */
1245 if (! sv_isobject(ST(0)))
1246 Perl_croak(aTHX_ "Usage: $thr->is_joinable()");
1248 thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1249 MUTEX_LOCK(&thread->mutex);
1250 ST(0) = ((thread->state & PERL_ITHR_FINISHED) &&
1251 ! (thread->state & (PERL_ITHR_DETACHED|PERL_ITHR_JOINED)))
1252 ? &PL_sv_yes : &PL_sv_no;
1253 MUTEX_UNLOCK(&thread->mutex);
1254 /* XSRETURN(1); - implied */
1258 ithread_wantarray(...)
1262 thread = SV_to_ithread(aTHX_ ST(0));
1263 MUTEX_LOCK(&thread->mutex);
1264 ST(0) = (thread->gimme & G_ARRAY) ? &PL_sv_yes :
1265 (thread->gimme & G_VOID) ? &PL_sv_undef
1266 /* G_SCALAR */ : &PL_sv_no;
1267 MUTEX_UNLOCK(&thread->mutex);
1268 /* XSRETURN(1); - implied */
1270 #endif /* USE_ITHREADS */
1276 /* The 'main' thread is thread 0.
1277 * It is detached (unjoinable) and immortal.
1283 PL_perl_destruct_level = 2;
1284 MUTEX_INIT(&create_destruct_mutex);
1285 MUTEX_LOCK(&create_destruct_mutex);
1287 PL_threadhook = &Perl_ithread_hook;
1289 thread = (ithread *)PerlMemShared_malloc(sizeof(ithread));
1291 PerlLIO_write(PerlIO_fileno(Perl_error_log), PL_no_mem, strlen(PL_no_mem));
1294 Zero(thread, 1, ithread);
1296 MUTEX_INIT(&thread->mutex);
1298 thread->tid = tid_counter++; /* Thread 0 */
1300 /* Head of the threads list */
1302 thread->next = thread;
1303 thread->prev = thread;
1305 thread->count = 1; /* Immortal */
1307 thread->interp = aTHX;
1308 thread->state = PERL_ITHR_DETACHED; /* Detached */
1309 thread->stack_size = default_stack_size;
1311 thread->thr = GetCurrentThreadId();
1313 thread->thr = pthread_self();
1316 S_ithread_set(aTHX_ thread);
1317 MUTEX_UNLOCK(&create_destruct_mutex);
1318 #endif /* USE_ITHREADS */