This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
threads 1.35 - Borland compiler fix
[perl5.git] / ext / threads / threads.xs
1 #define PERL_NO_GET_CONTEXT
2 #include "EXTERN.h"
3 #include "perl.h"
4 #include "XSUB.h"
5 /* Workaround for XSUB.h bug under WIN32 */
6 #ifdef WIN32
7 #  undef setjmp
8 #  if !defined(__BORLANDC__)
9 #    define setjmp(x) _setjmp(x)
10 #  endif
11 #endif
12 #ifdef HAS_PPPORT_H
13 #  define NEED_PL_signals
14 #  define NEED_newRV_noinc
15 #  define NEED_sv_2pv_nolen
16 #  include "ppport.h"
17 #  include "threads.h"
18 #endif
19
20 #ifdef USE_ITHREADS
21
22 #ifdef WIN32
23 #  include <windows.h>
24    /* Supposed to be in Winbase.h */
25 #  ifndef STACK_SIZE_PARAM_IS_A_RESERVATION
26 #    define STACK_SIZE_PARAM_IS_A_RESERVATION 0x00010000
27 #  endif
28 #  include <win32thread.h>
29 #else
30 #  ifdef OS2
31 typedef perl_os_thread pthread_t;
32 #  else
33 #    include <pthread.h>
34 #  endif
35 #  include <thread.h>
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))
39 #  else
40 #    define PERL_THREAD_DETACH(t) pthread_detach((t))
41 #  endif
42 #endif
43 #if !defined(HAS_GETPAGESIZE) && defined(I_SYS_PARAM)
44 #  include <sys/param.h>
45 #endif
46
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
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 */
64 #ifdef WIN32
65     DWORD  thr;                 /* OS's idea if thread id */
66     HANDLE handle;              /* OS's waitable handle */
67 #else
68     pthread_t thr;              /* OS's handle for the thread */
69 #endif
70     IV stack_size;
71 } ithread;
72
73
74 /* Used by Perl interpreter for thread context switching */
75 #define MY_CXT_KEY "threads::_guts" XS_VERSION
76
77 typedef struct {
78     ithread *thread;
79 } my_cxt_t;
80
81 START_MY_CXT
82
83
84 /* Linked list of all threads */
85 static ithread *threads;
86
87 /* Protects the creation and destruction of threads*/
88 static perl_mutex create_destruct_mutex;
89
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;
96 #else
97 static IV default_stack_size = 0;
98 #endif
99 static IV page_size = 0;
100
101
102 /* Used by Perl interpreter for thread context switching */
103 static void
104 S_ithread_set(pTHX_ ithread *thread)
105 {
106     dMY_CXT;
107     MY_CXT.thread = thread;
108 }
109
110 static ithread *
111 S_ithread_get(pTHX)
112 {
113     dMY_CXT;
114     return (MY_CXT.thread);
115 }
116
117
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.
121  */
122 static void
123 S_ithread_clear(pTHX_ ithread *thread)
124 {
125     PerlInterpreter *interp;
126
127     assert((thread->state & PERL_ITHR_FINISHED) &&
128            (thread->state & (PERL_ITHR_DETACHED|PERL_ITHR_JOINED)));
129
130     interp = thread->interp;
131     if (interp) {
132         dTHXa(interp);
133
134         PERL_SET_CONTEXT(interp);
135         S_ithread_set(aTHX_ thread);
136
137         SvREFCNT_dec(thread->params);
138         thread->params = Nullsv;
139
140         perl_destruct(interp);
141         thread->interp = NULL;
142     }
143     if (interp)
144         perl_free(interp);
145
146     PERL_SET_CONTEXT(aTHX);
147 }
148
149
150 /* Free an ithread structure and any attached data if its count == 0 */
151 static void
152 S_ithread_destruct(pTHX_ ithread *thread)
153 {
154 #ifdef WIN32
155     HANDLE handle;
156 #endif
157
158     MUTEX_LOCK(&thread->mutex);
159
160     /* Thread is still in use */
161     if (thread->count != 0) {
162         MUTEX_UNLOCK(&thread->mutex);
163         return;
164     }
165
166     /* Main thread (0) is immortal and should never get here */
167     assert(thread->tid != 0);
168
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;
173     thread->next = NULL;
174     thread->prev = NULL;
175     MUTEX_UNLOCK(&create_destruct_mutex);
176
177     /* Thread is now disowned */
178     S_ithread_clear(aTHX_ thread);
179
180 #ifdef WIN32
181     handle = thread->handle;
182     thread->handle = NULL;
183 #endif
184     MUTEX_UNLOCK(&thread->mutex);
185     MUTEX_DESTROY(&thread->mutex);
186
187 #ifdef WIN32
188     if (handle)
189         CloseHandle(handle);
190 #endif
191
192     /* Call PerlMemShared_free() in the context of the "first" interpreter
193      * per http://www.nntp.perl.org/group/perl.perl5.porters/110772
194      */
195     aTHX = PL_curinterp;
196     PerlMemShared_free(thread);
197 }
198
199
200 /* Called on exit */
201 int
202 Perl_ithread_hook(pTHX)
203 {
204     int veto_cleanup = 0;
205     MUTEX_LOCK(&create_destruct_mutex);
206     if ((aTHX == PL_curinterp) &&
207         (running_threads || joinable_threads))
208     {
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",
214                             running_threads,
215                             joinable_threads,
216                             detached_threads);
217         }
218         veto_cleanup = 1;
219     }
220     MUTEX_UNLOCK(&create_destruct_mutex);
221     return (veto_cleanup);
222 }
223
224
225 /* MAGIC (in mg.h sense) hooks */
226
227 int
228 ithread_mg_get(pTHX_ SV *sv, MAGIC *mg)
229 {
230     ithread *thread = (ithread *)mg->mg_ptr;
231     SvIV_set(sv, PTR2IV(thread));
232     SvIOK_on(sv);
233     return (0);
234 }
235
236 int
237 ithread_mg_free(pTHX_ SV *sv, MAGIC *mg)
238 {
239     ithread *thread = (ithread *)mg->mg_ptr;
240     int cleanup;
241
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);
247
248     if (cleanup)
249         S_ithread_destruct(aTHX_ thread);
250     return (0);
251 }
252
253 int
254 ithread_mg_dup(pTHX_ MAGIC *mg, CLONE_PARAMS *param)
255 {
256     ithread *thread = (ithread *)mg->mg_ptr;
257     MUTEX_LOCK(&thread->mutex);
258     thread->count++;
259     MUTEX_UNLOCK(&thread->mutex);
260     return (0);
261 }
262
263 MGVTBL ithread_vtbl = {
264     ithread_mg_get,     /* get */
265     0,                  /* set */
266     0,                  /* len */
267     0,                  /* clear */
268     ithread_mg_free,    /* free */
269     0,                  /* copy */
270     ithread_mg_dup      /* dup */
271 };
272
273
274 /* Provided default, minimum and rational stack sizes */
275 static IV
276 good_stack_size(pTHX_ IV stack_size)
277 {
278     /* Use default stack size if no stack size specified */
279     if (! stack_size)
280         return (default_stack_size);
281
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);
287         }
288         return (PTHREAD_STACK_MIN);
289     }
290 #endif
291
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);
296 #  ifdef _SC_PAGESIZE
297         page_size = sysconf(_SC_PAGESIZE);
298 #  else
299         page_size = sysconf(_SC_MMAP_PAGE_SIZE);
300 #  endif
301         if ((long)page_size < 0) {
302             if (errno) {
303                 SV * const error = get_sv("@", FALSE);
304                 (void)SvUPGRADE(error, SVt_PV);
305                 Perl_croak(aTHX_ "PANIC: sysconf: %s", SvPV_nolen(error));
306             } else {
307                 Perl_croak(aTHX_ "PANIC: sysconf: pagesize unknown");
308             }
309         }
310 #else
311 #  ifdef HAS_GETPAGESIZE
312         page_size = getpagesize();
313 #  else
314 #    if defined(I_SYS_PARAM) && defined(PAGESIZE)
315         page_size = PAGESIZE;
316 #    else
317         page_size = 8192;   /* A conservative default */
318 #    endif
319 #  endif
320         if (page_size <= 0)
321             Perl_croak(aTHX_ "PANIC: bad pagesize %" IVdf, (IV)page_size);
322 #endif
323     }
324     stack_size = ((stack_size + (page_size - 1)) / page_size) * page_size;
325
326     return (stack_size);
327 }
328
329
330 /* Starts executing the thread.
331  * Passed as the C level function to run in the new thread.
332  */
333 #ifdef WIN32
334 static THREAD_RET_TYPE
335 S_ithread_run(LPVOID arg)
336 #else
337 static void *
338 S_ithread_run(void * arg)
339 #endif
340 {
341     ithread *thread = (ithread *)arg;
342     int cleanup;
343
344     dTHXa(thread->interp);
345     PERL_SET_CONTEXT(thread->interp);
346     S_ithread_set(aTHX_ thread);
347
348 #if 0
349     /* Far from clear messing with ->thr child-side is a good idea */
350     MUTEX_LOCK(&thread->mutex);
351 #ifdef WIN32
352     thread->thr = GetCurrentThreadId();
353 #else
354     thread->thr = pthread_self();
355 #endif
356     MUTEX_UNLOCK(&thread->mutex);
357 #endif
358
359     PL_perl_destruct_level = 2;
360
361     {
362         AV *params = (AV *)SvRV(thread->params);
363         int len = (int)av_len(params)+1;
364         int ii;
365         int jmp_rc = 0;
366         I32 oldscope;
367
368         dJMPENV;
369
370         dSP;
371         ENTER;
372         SAVETMPS;
373
374         /* Put args on the stack */
375         PUSHMARK(SP);
376         for (ii=0; ii < len; ii++) {
377             XPUSHs(av_shift(params));
378         }
379         PUTBACK;
380
381         oldscope = PL_scopestack_ix;
382         JMPENV_PUSH(jmp_rc);
383         if (jmp_rc == 0) {
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) {
388                 LEAVE;
389             }
390         }
391         JMPENV_POP;
392
393         /* Remove args from stack and put back in params array */
394         SPAGAIN;
395         for (ii=len-1; ii >= 0; ii--) {
396             SV *sv = POPs;
397             if (jmp_rc == 0) {
398                 av_store(params, ii, SvREFCNT_inc(sv));
399             }
400         }
401
402         FREETMPS;
403         LEAVE;
404
405         /* Check for failure */
406         if (SvTRUE(ERRSV) && ckWARN_d(WARN_THREADS)) {
407             oldscope = PL_scopestack_ix;
408             JMPENV_PUSH(jmp_rc);
409             if (jmp_rc == 0) {
410                 Perl_warn(aTHX_ "Thread %" UVuf " terminated abnormally: %" SVf, thread->tid, ERRSV);
411             } else if (jmp_rc == 2) {
412                 while (PL_scopestack_ix > oldscope) {
413                     LEAVE;
414                 }
415             }
416             JMPENV_POP;
417         }
418
419         /* Release function ref */
420         SvREFCNT_dec(thread->init_function);
421         thread->init_function = Nullsv;
422     }
423
424     PerlIO_flush((PerlIO *)NULL);
425
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);
432
433     if (cleanup) {
434         MUTEX_LOCK(&create_destruct_mutex);
435         detached_threads--;
436         MUTEX_UNLOCK(&create_destruct_mutex);
437         S_ithread_destruct(aTHX_ thread);
438     } else {
439         MUTEX_LOCK(&create_destruct_mutex);
440         running_threads--;
441         joinable_threads++;
442         MUTEX_UNLOCK(&create_destruct_mutex);
443     }
444
445 #ifdef WIN32
446     return ((DWORD)0);
447 #else
448     return (0);
449 #endif
450 }
451
452
453 /* Type conversion helper functions */
454 static SV *
455 ithread_to_SV(pTHX_ SV *obj, ithread *thread, char *classname, bool inc)
456 {
457     SV *sv;
458     MAGIC *mg;
459
460     if (inc) {
461         MUTEX_LOCK(&thread->mutex);
462         thread->count++;
463         MUTEX_UNLOCK(&thread->mutex);
464     }
465
466     if (! obj) {
467         obj = newSV(0);
468     }
469
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;
474     SvREADONLY_on(sv);
475
476     return (obj);
477 }
478
479 static ithread *
480 SV_to_ithread(pTHX_ SV *sv)
481 {
482     /* Argument is a thread */
483     if (SvROK(sv)) {
484       return (INT2PTR(ithread *, SvIV(SvRV(sv))));
485     }
486     /* Argument is classname, therefore return current thread */
487     return (S_ithread_get(aTHX));
488 }
489
490
491 /* threads->create()
492  * Called in context of parent thread.
493  */
494 static SV *
495 S_ithread_create(
496         pTHX_ SV *obj,
497         char     *classname,
498         SV       *init_function,
499         IV        stack_size,
500         int       gimme,
501         SV       *params)
502 {
503     ithread     *thread;
504     CLONE_PARAMS clone_param;
505     ithread     *current_thread = S_ithread_get(aTHX);
506
507     SV         **tmps_tmp = PL_tmps_stack;
508     IV           tmps_ix  = PL_tmps_ix;
509 #ifndef WIN32
510     int          rc_stack_size = 0;
511     int          rc_thread_create = 0;
512 #endif
513
514     MUTEX_LOCK(&create_destruct_mutex);
515
516     /* Allocate thread structure */
517     thread = (ithread *)PerlMemShared_malloc(sizeof(ithread));
518     if (!thread) {
519         MUTEX_UNLOCK(&create_destruct_mutex);
520         PerlLIO_write(PerlIO_fileno(Perl_error_log), PL_no_mem, strlen(PL_no_mem));
521         my_exit(1);
522     }
523     Zero(thread, 1, ithread);
524
525     /* Add to threads list */
526     thread->next = threads;
527     thread->prev = threads->prev;
528     threads->prev = thread;
529     thread->prev->next = thread;
530
531     /* Set count to 1 immediately in case thread exits before
532      * we return to caller!
533      */
534     thread->count = 1;
535
536     MUTEX_INIT(&thread->mutex);
537     thread->tid = tid_counter++;
538     thread->stack_size = good_stack_size(aTHX_ stack_size);
539     thread->gimme = gimme;
540
541     /* "Clone" our interpreter into the thread's interpreter.
542      * This gives thread access to "static data" and code.
543      */
544     PerlIO_flush((PerlIO *)NULL);
545     S_ithread_set(aTHX_ thread);
546
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 */
550
551 #ifdef WIN32
552     thread->interp = perl_clone(aTHX, CLONEf_KEEP_PTR_TABLE | CLONEf_CLONE_HOST);
553 #else
554     thread->interp = perl_clone(aTHX, CLONEf_KEEP_PTR_TABLE);
555 #endif
556
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.
560      */
561     {
562         dTHXa(thread->interp);
563
564         MY_CXT_CLONE;
565
566         /* Here we remove END blocks since they should only run in the thread
567          * they are created
568          */
569         SvREFCNT_dec(PL_endav);
570         PL_endav = newAV();
571
572         if (SvPOK(init_function)) {
573             thread->init_function = newSV(0);
574             sv_copypv(thread->init_function, init_function);
575         } else {
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);
580             }
581         }
582
583         thread->params = sv_dup(params, &clone_param);
584         SvREFCNT_inc(thread->params);
585
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
588          * higher than 0.
589          *
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.
594          *
595          * Example of this can be found in bugreport 15837 where calls in the
596          * parameter list end up as a temp.
597          *
598          * One could argue that this fix should be in perl_clone.
599          */
600         while (tmps_ix > 0) {
601             SV* sv = (SV*)ptr_table_fetch(PL_ptr_table, tmps_tmp[tmps_ix]);
602             tmps_ix--;
603             if (sv && SvREFCNT(sv) == 0) {
604                 SvREFCNT_inc(sv);
605                 SvREFCNT_dec(sv);
606             }
607         }
608
609         SvTEMP_off(thread->init_function);
610         ptr_table_free(PL_ptr_table);
611         PL_ptr_table = NULL;
612         PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
613     }
614     S_ithread_set(aTHX_ current_thread);
615     PERL_SET_CONTEXT(aTHX);
616
617     /* Create/start the thread */
618 #ifdef WIN32
619     thread->handle = CreateThread(NULL,
620                                   (DWORD)thread->stack_size,
621                                   S_ithread_run,
622                                   (LPVOID)thread,
623                                   STACK_SIZE_PARAM_IS_A_RESERVATION,
624                                   &thread->thr);
625 #else
626     {
627         static pthread_attr_t attr;
628         static int attr_inited = 0;
629         static int attr_joinable = PTHREAD_CREATE_JOINABLE;
630         if (! attr_inited) {
631             pthread_attr_init(&attr);
632             attr_inited = 1;
633         }
634
635 #  ifdef PTHREAD_ATTR_SETDETACHSTATE
636         /* Threads start out joinable */
637         PTHREAD_ATTR_SETDETACHSTATE(&attr, attr_joinable);
638 #  endif
639
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);
644         }
645 #  endif
646
647         /* Create the thread */
648         if (! rc_stack_size) {
649 #  ifdef OLD_PTHREADS_API
650             rc_thread_create = pthread_create(&thread->thr,
651                                               attr,
652                                               S_ithread_run,
653                                               (void *)thread);
654 #  else
655 #    if defined(HAS_PTHREAD_ATTR_SETSCOPE) && defined(PTHREAD_SCOPE_SYSTEM)
656             pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);
657 #    endif
658             rc_thread_create = pthread_create(&thread->thr,
659                                               &attr,
660                                               S_ithread_run,
661                                               (void *)thread);
662 #  endif
663         }
664
665 #  ifdef _POSIX_THREAD_ATTR_STACKSIZE
666         /* Try to get thread's actual stack size */
667         {
668             size_t stacksize;
669 #ifdef HPUX1020
670             stacksize = pthread_attr_getstacksize(attr);
671 #else
672             if (! pthread_attr_getstacksize(&attr, &stacksize))
673 #endif
674                 if (stacksize > 0) {
675                     thread->stack_size = (IV)stacksize;
676                 }
677         }
678 #  endif
679     }
680 #endif
681
682     /* Check for errors */
683 #ifdef WIN32
684     if (thread->handle == NULL) {
685 #else
686     if (rc_stack_size || rc_thread_create) {
687 #endif
688         MUTEX_UNLOCK(&create_destruct_mutex);
689         sv_2mortal(params);
690         S_ithread_destruct(aTHX_ thread);
691 #ifndef WIN32
692         if (ckWARN_d(WARN_THREADS)) {
693             if (rc_stack_size)
694                 Perl_warn(aTHX_ "Thread creation failed: pthread_attr_setstacksize(%" IVdf ") returned %d", thread->stack_size, rc_stack_size);
695             else
696                 Perl_warn(aTHX_ "Thread creation failed: pthread_create returned %d", rc_thread_create);
697         }
698 #endif
699         return (&PL_sv_undef);
700     }
701
702     running_threads++;
703     MUTEX_UNLOCK(&create_destruct_mutex);
704
705     sv_2mortal(params);
706
707     return (ithread_to_SV(aTHX_ obj, thread, classname, FALSE));
708 }
709
710 #endif /* USE_ITHREADS */
711
712
713 MODULE = threads    PACKAGE = threads    PREFIX = ithread_
714 PROTOTYPES: DISABLE
715
716 #ifdef USE_ITHREADS
717
718 void
719 ithread_create(...)
720     PREINIT:
721         char *classname;
722         ithread *thread;
723         SV *function_to_call;
724         AV *params;
725         HV *specs;
726         IV stack_size;
727         int context;
728         char *str;
729         int idx;
730         int ii;
731     CODE:
732         if ((items >= 2) && SvROK(ST(1)) && SvTYPE(SvRV(ST(1)))==SVt_PVHV) {
733             if (--items < 2)
734                 Perl_croak(aTHX_ "Usage: threads->create(\\%specs, function, ...)");
735             specs = (HV*)SvRV(ST(1));
736             idx = 1;
737         } else {
738             if (items < 2)
739                 Perl_croak(aTHX_ "Usage: threads->create(function, ...)");
740             specs = NULL;
741             idx = 0;
742         }
743
744         if (sv_isobject(ST(0))) {
745             /* $thr->create() */
746             classname = HvNAME(SvSTASH(SvRV(ST(0))));
747             thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
748             stack_size = thread->stack_size;
749         } else {
750             /* threads->create() */
751             classname = (char *)SvPV_nolen(ST(0));
752             stack_size = default_stack_size;
753         }
754
755         function_to_call = ST(idx+1);
756
757         context = -1;
758         if (specs) {
759             /* stack_size */
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));
766             }
767
768             /* context */
769             if (hv_exists(specs, "context", 7)) {
770                 str = (char *)SvPV_nolen(*hv_fetch(specs, "context", 7, 0));
771                 switch (*str) {
772                     case 'a':
773                     case 'A':
774                         context = G_ARRAY;
775                         break;
776                     case 's':
777                     case 'S':
778                         context = G_SCALAR;
779                         break;
780                     case 'v':
781                     case 'V':
782                         context = G_VOID;
783                         break;
784                     default:
785                         Perl_croak(aTHX_ "Invalid context: %s", str);
786                 }
787             } else if (hv_exists(specs, "array", 5)) {
788                 if (SvTRUE(*hv_fetch(specs, "array", 5, 0))) {
789                     context = G_ARRAY;
790                 }
791             } else if (hv_exists(specs, "scalar", 6)) {
792                 if (SvTRUE(*hv_fetch(specs, "scalar", 6, 0))) {
793                     context = G_SCALAR;
794                 }
795             } else if (hv_exists(specs, "void", 4)) {
796                 if (SvTRUE(*hv_fetch(specs, "void", 4, 0))) {
797                     context = G_VOID;
798                 }
799             }
800         }
801         if (context == -1) {
802             context = GIMME_V;  /* Implicit context */
803         } else {
804             context |= (GIMME_V & (~(G_ARRAY|G_SCALAR|G_VOID)));
805         }
806
807         /* Function args */
808         params = newAV();
809         if (items > 2) {
810             for (ii=2; ii < items ; ii++) {
811                 av_push(params, SvREFCNT_inc(ST(idx+ii)));
812             }
813         }
814
815         /* Create thread */
816         ST(0) = sv_2mortal(S_ithread_create(aTHX_ Nullsv,
817                                             classname,
818                                             function_to_call,
819                                             stack_size,
820                                             context,
821                                             newRV_noinc((SV*)params)));
822         /* XSRETURN(1); - implied */
823
824
825 void
826 ithread_list(...)
827     PREINIT:
828         char *classname;
829         ithread *thread;
830         int list_context;
831         IV count = 0;
832         int want_running;
833     PPCODE:
834         /* Class method only */
835         if (SvROK(ST(0)))
836             Perl_croak(aTHX_ "Usage: threads->list(...)");
837         classname = (char *)SvPV_nolen(ST(0));
838
839         /* Calling context */
840         list_context = (GIMME_V == G_ARRAY);
841
842         /* Running or joinable parameter */
843         if (items > 1) {
844             want_running = SvTRUE(ST(1));
845         }
846
847         /* Walk through threads list */
848         MUTEX_LOCK(&create_destruct_mutex);
849         for (thread = threads->next;
850              thread != threads;
851              thread = thread->next)
852         {
853             /* Ignore detached or joined threads */
854             if (thread->state & (PERL_ITHR_DETACHED|PERL_ITHR_JOINED)) {
855                 continue;
856             }
857
858             /* Filter per parameter */
859             if (items > 1) {
860                 if (want_running) {
861                     if (thread->state & PERL_ITHR_FINISHED) {
862                         continue;   /* Not running */
863                     }
864                 } else {
865                     if (! (thread->state & PERL_ITHR_FINISHED)) {
866                         continue;   /* Still running - not joinable yet */
867                     }
868                 }
869             }
870
871             /* Push object on stack if list context */
872             if (list_context) {
873                 XPUSHs(sv_2mortal(ithread_to_SV(aTHX_ Nullsv, thread, classname, TRUE)));
874             }
875             count++;
876         }
877         MUTEX_UNLOCK(&create_destruct_mutex);
878         /* If scalar context, send back count */
879         if (! list_context) {
880             XSRETURN_IV(count);
881         }
882
883
884 void
885 ithread_self(...)
886     PREINIT:
887         char *classname;
888         ithread *thread;
889     CODE:
890         /* Class method only */
891         if (SvROK(ST(0)))
892             Perl_croak(aTHX_ "Usage: threads->self()");
893         classname = (char *)SvPV_nolen(ST(0));
894
895         thread = S_ithread_get(aTHX);
896
897         ST(0) = sv_2mortal(ithread_to_SV(aTHX_ Nullsv, thread, classname, TRUE));
898         /* XSRETURN(1); - implied */
899
900
901 void
902 ithread_tid(...)
903     PREINIT:
904         ithread *thread;
905     CODE:
906         thread = SV_to_ithread(aTHX_ ST(0));
907         XST_mUV(0, thread->tid);
908         /* XSRETURN(1); - implied */
909
910
911 void
912 ithread_join(...)
913     PREINIT:
914         ithread *thread;
915         int join_err;
916         AV *params;
917         int len;
918         int ii;
919 #ifdef WIN32
920         DWORD waitcode;
921 #else
922         void *retval;
923 #endif
924     PPCODE:
925         /* Object method only */
926         if (! sv_isobject(ST(0)))
927             Perl_croak(aTHX_ "Usage: $thr->join()");
928
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);
934         if (join_err) {
935             if (join_err & PERL_ITHR_DETACHED) {
936                 Perl_croak(aTHX_ "Cannot join a detached thread");
937             } else {
938                 Perl_croak(aTHX_ "Thread already joined");
939             }
940         }
941
942         /* Join the thread */
943 #ifdef WIN32
944         waitcode = WaitForSingleObject(thread->handle, INFINITE);
945 #else
946         pthread_join(thread->thr, &retval);
947 #endif
948
949         MUTEX_LOCK(&thread->mutex);
950         /* Mark as joined */
951         thread->state |= PERL_ITHR_JOINED;
952
953         /* Get the return value from the call_sv */
954         {
955             AV *params_copy;
956             PerlInterpreter *other_perl;
957             CLONE_PARAMS clone_params;
958             ithread *current_thread;
959
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);
976             PL_ptr_table = NULL;
977         }
978
979         /* We are finished with the thread */
980         S_ithread_clear(aTHX_ thread);
981         MUTEX_UNLOCK(&thread->mutex);
982
983         MUTEX_LOCK(&create_destruct_mutex);
984         joinable_threads--;
985         MUTEX_UNLOCK(&create_destruct_mutex);
986
987         /* If no return values, then just return */
988         if (! params) {
989             XSRETURN_UNDEF;
990         }
991
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));
997         }
998
999         /* Free return value array */
1000         SvREFCNT_dec(params);
1001
1002
1003 void
1004 ithread_yield(...)
1005     CODE:
1006         YIELD;
1007
1008
1009 void
1010 ithread_detach(...)
1011     PREINIT:
1012         ithread *thread;
1013         int detach_err;
1014         int cleanup;
1015     CODE:
1016         thread = SV_to_ithread(aTHX_ ST(0));
1017         MUTEX_LOCK(&thread->mutex);
1018
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");
1024             } else {
1025                 Perl_croak(aTHX_ "Cannot detach a joined thread");
1026             }
1027         }
1028
1029         /* Detach the thread */
1030         thread->state |= PERL_ITHR_DETACHED;
1031 #ifdef WIN32
1032         /* Windows has no 'detach thread' function */
1033 #else
1034         PERL_THREAD_DETACH(thread->thr);
1035 #endif
1036         /* Cleanup if finished */
1037         cleanup = (thread->state & PERL_ITHR_FINISHED);
1038         MUTEX_UNLOCK(&thread->mutex);
1039
1040         MUTEX_LOCK(&create_destruct_mutex);
1041         if (cleanup) {
1042             joinable_threads--;
1043         } else {
1044             running_threads--;
1045             detached_threads++;
1046         }
1047         MUTEX_UNLOCK(&create_destruct_mutex);
1048
1049         if (cleanup) {
1050             S_ithread_destruct(aTHX_ thread);
1051         }
1052
1053
1054 void
1055 ithread_kill(...)
1056     PREINIT:
1057         ithread *thread;
1058         char *sig_name;
1059         IV signal;
1060     CODE:
1061         /* Must have safe signals */
1062         if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
1063             Perl_croak(aTHX_ "Cannot signal threads without safe signals");
1064
1065         /* Object method only */
1066         if (! sv_isobject(ST(0)))
1067             Perl_croak(aTHX_ "Usage: $thr->kill('SIG...')");
1068
1069         /* Get signal */
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')
1073                 sig_name += 3;
1074             if ((signal = whichsig(sig_name)) < 0)
1075                 Perl_croak(aTHX_ "Unrecognized signal name: %s", sig_name);
1076         } else
1077             signal = SvIV(ST(1));
1078
1079         /* Set the signal for the thread */
1080         thread = SV_to_ithread(aTHX_ ST(0));
1081         MUTEX_LOCK(&thread->mutex);
1082         {
1083             dTHXa(thread->interp);
1084             PL_psig_pend[signal]++;
1085             PL_sig_pending = 1;
1086         }
1087         MUTEX_UNLOCK(&thread->mutex);
1088
1089         /* Return the thread to allow for method chaining */
1090         ST(0) = ST(0);
1091         /* XSRETURN(1); - implied */
1092
1093
1094 void
1095 ithread_DESTROY(...)
1096     CODE:
1097         sv_unmagic(SvRV(ST(0)), PERL_MAGIC_shared_scalar);
1098
1099
1100 void
1101 ithread_equal(...)
1102     PREINIT:
1103         int are_equal = 0;
1104     CODE:
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);
1110         }
1111         if (are_equal) {
1112             XST_mYES(0);
1113         } else {
1114             /* Return 0 on false for backward compatibility */
1115             XST_mIV(0, 0);
1116         }
1117         /* XSRETURN(1); - implied */
1118
1119
1120 void
1121 ithread_object(...)
1122     PREINIT:
1123         char *classname;
1124         UV tid;
1125         ithread *thread;
1126         int found = 0;
1127     CODE:
1128         /* Class method only */
1129         if (SvROK(ST(0)))
1130             Perl_croak(aTHX_ "Usage: threads->object($tid)");
1131         classname = (char *)SvPV_nolen(ST(0));
1132
1133         if ((items < 2) || ! SvOK(ST(1))) {
1134             XSRETURN_UNDEF;
1135         }
1136
1137         /* threads->object($tid) */
1138         tid = SvUV(ST(1));
1139
1140         /* Walk through threads list */
1141         MUTEX_LOCK(&create_destruct_mutex);
1142         for (thread = threads->next;
1143              thread != threads;
1144              thread = thread->next)
1145         {
1146             /* Look for TID, but ignore detached or joined threads */
1147             if ((thread->tid != tid) ||
1148                 (thread->state & (PERL_ITHR_DETACHED|PERL_ITHR_JOINED)))
1149             {
1150                 continue;
1151             }
1152             /* Put object on stack */
1153             ST(0) = sv_2mortal(ithread_to_SV(aTHX_ Nullsv, thread, classname, TRUE));
1154             found = 1;
1155             break;
1156         }
1157         MUTEX_UNLOCK(&create_destruct_mutex);
1158         if (! found) {
1159             XSRETURN_UNDEF;
1160         }
1161         /* XSRETURN(1); - implied */
1162
1163
1164 void
1165 ithread__handle(...);
1166     PREINIT:
1167         ithread *thread;
1168     CODE:
1169         thread = SV_to_ithread(aTHX_ ST(0));
1170 #ifdef WIN32
1171         XST_mUV(0, PTR2UV(&thread->handle));
1172 #else
1173         XST_mUV(0, PTR2UV(&thread->thr));
1174 #endif
1175         /* XSRETURN(1); - implied */
1176
1177
1178 void
1179 ithread_get_stack_size(...)
1180     PREINIT:
1181         IV stack_size;
1182     CODE:
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;
1187         } else {
1188             /* threads->get_stack_size() */
1189             stack_size = default_stack_size;
1190         }
1191         XST_mIV(0, stack_size);
1192         /* XSRETURN(1); - implied */
1193
1194
1195 void
1196 ithread_set_stack_size(...)
1197     PREINIT:
1198         IV old_size;
1199     CODE:
1200         if (items != 2)
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");
1204
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 */
1209
1210
1211 void
1212 ithread_is_running(...)
1213     PREINIT:
1214         ithread *thread;
1215     CODE:
1216         /* Object method only */
1217         if (! sv_isobject(ST(0)))
1218             Perl_croak(aTHX_ "Usage: $thr->is_running()");
1219
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 */
1225
1226
1227 void
1228 ithread_is_detached(...)
1229     PREINIT:
1230         ithread *thread;
1231     CODE:
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 */
1237
1238
1239 void
1240 ithread_is_joinable(...)
1241     PREINIT:
1242         ithread *thread;
1243     CODE:
1244         /* Object method only */
1245         if (! sv_isobject(ST(0)))
1246             Perl_croak(aTHX_ "Usage: $thr->is_joinable()");
1247
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 */
1255
1256
1257 void
1258 ithread_wantarray(...)
1259     PREINIT:
1260         ithread *thread;
1261     CODE:
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 */
1269
1270 #endif /* USE_ITHREADS */
1271
1272
1273 BOOT:
1274 {
1275 #ifdef USE_ITHREADS
1276     /* The 'main' thread is thread 0.
1277      * It is detached (unjoinable) and immortal.
1278      */
1279
1280     ithread *thread;
1281     MY_CXT_INIT;
1282
1283     PL_perl_destruct_level = 2;
1284     MUTEX_INIT(&create_destruct_mutex);
1285     MUTEX_LOCK(&create_destruct_mutex);
1286
1287     PL_threadhook = &Perl_ithread_hook;
1288
1289     thread = (ithread *)PerlMemShared_malloc(sizeof(ithread));
1290     if (! thread) {
1291         PerlLIO_write(PerlIO_fileno(Perl_error_log), PL_no_mem, strlen(PL_no_mem));
1292         my_exit(1);
1293     }
1294     Zero(thread, 1, ithread);
1295
1296     MUTEX_INIT(&thread->mutex);
1297
1298     thread->tid = tid_counter++;        /* Thread 0 */
1299
1300     /* Head of the threads list */
1301     threads = thread;
1302     thread->next = thread;
1303     thread->prev = thread;
1304
1305     thread->count = 1;                  /* Immortal */
1306
1307     thread->interp = aTHX;
1308     thread->state = PERL_ITHR_DETACHED; /* Detached */
1309     thread->stack_size = default_stack_size;
1310 #  ifdef WIN32
1311     thread->thr = GetCurrentThreadId();
1312 #  else
1313     thread->thr = pthread_self();
1314 #  endif
1315
1316     S_ithread_set(aTHX_ thread);
1317     MUTEX_UNLOCK(&create_destruct_mutex);
1318 #endif /* USE_ITHREADS */
1319 }