There is no pthread_sigmask on VMS, so use sigprocmask instead.
[p5sagit/p5-mst-13.2.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_flags
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_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 */
54
55 #define PERL_ITHR_UNCALLABLE  (PERL_ITHR_DETACHED|PERL_ITHR_JOINED)
56
57
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 */
69 #ifdef WIN32
70     DWORD  thr;                 /* OS's idea if thread id */
71     HANDLE handle;              /* OS's waitable handle */
72 #else
73     pthread_t thr;              /* OS's handle for the thread */
74 #endif
75     IV stack_size;
76     SV *err;                    /* Error from abnormally terminated thread */
77     char *err_class;            /* Error object's classname if applicable */
78     sigset_t initial_sigmask;   /* Thread wakes up with signals blocked */
79 } ithread;
80
81
82 #define MY_CXT_KEY "threads::_cxt" XS_VERSION
83
84 typedef struct {
85     /* Used by Perl interpreter for thread context switching */
86     ithread *context;
87 } my_cxt_t;
88
89 START_MY_CXT
90
91
92 #define MY_POOL_KEY "threads::_pool" XS_VERSION
93
94 typedef struct {
95     /* Structure for 'main' thread
96      * Also forms the 'base' for the doubly-linked list of threads */
97     ithread main_thread;
98
99     /* Protects the creation and destruction of threads*/
100     perl_mutex create_destruct_mutex;
101
102     UV tid_counter;
103     IV joinable_threads;
104     IV running_threads;
105     IV detached_threads;
106     IV total_threads;
107     IV default_stack_size;
108     IV page_size;
109 } my_pool_t;
110
111 #define dMY_POOL \
112     SV *my_pool_sv = *hv_fetch(PL_modglobal, MY_POOL_KEY,               \
113                                sizeof(MY_POOL_KEY)-1, TRUE);            \
114     my_pool_t *my_poolp = INT2PTR(my_pool_t*, SvUV(my_pool_sv))
115
116 #define MY_POOL (*my_poolp)
117
118 /* Block most signals for calling thread, setting the old signal mask to
119  * oldmask, if it is not NULL */
120 STATIC int
121 S_block_most_signals(sigset_t *oldmask)
122 {
123     sigset_t newmask;
124
125     sigfillset(&newmask);
126     /* Don't block certain "important" signals (stolen from mg.c) */
127 #ifdef SIGILL
128     sigdelset(&newmask, SIGILL);
129 #endif
130 #ifdef SIGBUS
131     sigdelset(&newmask, SIGBUS);
132 #endif
133 #ifdef SIGSEGV
134     sigdelset(&newmask, SIGSEGV);
135 #endif
136
137 #ifdef WIN32
138     /* XXX: How to do this on win32? */
139     return 0;
140 #elif defined(VMS)
141     /* no per-thread blocking available */
142     return sigprocmask(SIG_BLOCK, &newmask, oldmask);
143 #else
144     return pthread_sigmask(SIG_BLOCK, &newmask, oldmask);
145 #endif /* WIN32 */
146 }
147
148 /* Set the signal mask for this thread to newmask */
149 STATIC int
150 S_set_sigmask(sigset_t *newmask)
151 {
152 #ifdef WIN32
153     /* XXX: How to do this on win32? */
154     return 0;
155 #elif defined(VMS)
156     return sigprocmask(SIG_SETMASK, newmask, NULL);
157 #else
158     return pthread_sigmask(SIG_SETMASK, newmask, NULL);
159 #endif /* WIN32 */
160 }
161
162 /* Used by Perl interpreter for thread context switching */
163 STATIC void
164 S_ithread_set(pTHX_ ithread *thread)
165 {
166     dMY_CXT;
167     MY_CXT.context = thread;
168 }
169
170 STATIC ithread *
171 S_ithread_get(pTHX)
172 {
173     dMY_CXT;
174     return (MY_CXT.context);
175 }
176
177
178 /* Free any data (such as the Perl interpreter) attached to an ithread
179  * structure.  This is a bit like undef on SVs, where the SV isn't freed,
180  * but the PVX is.  Must be called with thread->mutex already locked.  Also,
181  * must be called with MY_POOL.create_destruct_mutex unlocked as destruction
182  * of the interpreter can lead to recursive destruction calls that could
183  * lead to a deadlock on that mutex.
184  */
185 STATIC void
186 S_ithread_clear(pTHX_ ithread *thread)
187 {
188     PerlInterpreter *interp;
189     sigset_t origmask;
190
191     assert(((thread->state & PERL_ITHR_FINISHED) &&
192             (thread->state & PERL_ITHR_UNCALLABLE))
193                 ||
194            (thread->state & PERL_ITHR_NONVIABLE));
195
196     /* We temporarily set the interpreter context to the interpreter being
197      * destroyed.  It's in no condition to handle signals while it's being
198      * taken apart.
199      */
200     S_block_most_signals(&origmask);
201
202     interp = thread->interp;
203     if (interp) {
204         dTHXa(interp);
205
206         PERL_SET_CONTEXT(interp);
207         S_ithread_set(aTHX_ thread);
208
209         SvREFCNT_dec(thread->params);
210         thread->params = Nullsv;
211
212         if (thread->err) {
213             SvREFCNT_dec(thread->err);
214             thread->err = Nullsv;
215         }
216
217         perl_destruct(interp);
218         perl_free(interp);
219         thread->interp = NULL;
220     }
221
222     PERL_SET_CONTEXT(aTHX);
223     S_set_sigmask(&origmask);
224 }
225
226
227 /* Decrement the refcount of an ithread, and if it reaches zero, free it.
228  * Must be called with the mutex held.
229  * On return, mutex is released (or destroyed).
230  */
231 STATIC void
232 S_ithread_free(pTHX_ ithread *thread)
233 {
234 #ifdef WIN32
235     HANDLE handle;
236 #endif
237     dMY_POOL;
238
239     if (! (thread->state & PERL_ITHR_NONVIABLE)) {
240         assert(thread->count > 0);
241         if (--thread->count > 0) {
242             MUTEX_UNLOCK(&thread->mutex);
243             return;
244         }
245         assert((thread->state & PERL_ITHR_FINISHED) &&
246                (thread->state & PERL_ITHR_UNCALLABLE));
247     }
248     MUTEX_UNLOCK(&thread->mutex);
249
250     /* Main thread (0) is immortal and should never get here */
251     assert(thread->tid != 0);
252
253     /* Remove from circular list of threads */
254     MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
255     assert(thread->prev && thread->next);
256     thread->next->prev = thread->prev;
257     thread->prev->next = thread->next;
258     thread->next = NULL;
259     thread->prev = NULL;
260     MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
261
262     /* Thread is now disowned */
263     MUTEX_LOCK(&thread->mutex);
264     S_ithread_clear(aTHX_ thread);
265
266 #ifdef WIN32
267     handle = thread->handle;
268     thread->handle = NULL;
269 #endif
270     MUTEX_UNLOCK(&thread->mutex);
271     MUTEX_DESTROY(&thread->mutex);
272
273 #ifdef WIN32
274     if (handle) {
275         CloseHandle(handle);
276     }
277 #endif
278
279     PerlMemShared_free(thread);
280
281     /* total_threads >= 1 is used to veto cleanup by the main thread,
282      * should it happen to exit while other threads still exist.
283      * Decrement this as the very last thing in the thread's existence.
284      * Otherwise, MY_POOL and global state such as PL_op_mutex may get
285      * freed while we're still using it.
286      */
287     MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
288     MY_POOL.total_threads--;
289     MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
290 }
291
292
293 static void
294 S_ithread_count_inc(pTHX_ ithread *thread)
295 {
296     MUTEX_LOCK(&thread->mutex);
297     thread->count++;
298     MUTEX_UNLOCK(&thread->mutex);
299 }
300
301
302 /* Warn if exiting with any unjoined threads */
303 STATIC int
304 S_exit_warning(pTHX)
305 {
306     int veto_cleanup, warn;
307     dMY_POOL;
308
309     MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
310     veto_cleanup = (MY_POOL.total_threads > 0);
311     warn         = (MY_POOL.running_threads || MY_POOL.joinable_threads);
312     MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
313
314     if (warn) {
315         if (ckWARN_d(WARN_THREADS)) {
316             Perl_warn(aTHX_ "Perl exited with active threads:\n\t%"
317                             IVdf " running and unjoined\n\t%"
318                             IVdf " finished and unjoined\n\t%"
319                             IVdf " running and detached\n",
320                             MY_POOL.running_threads,
321                             MY_POOL.joinable_threads,
322                             MY_POOL.detached_threads);
323         }
324     }
325
326     return (veto_cleanup);
327 }
328
329
330 /* Called from perl_destruct() in each thread.  If it's the main thread,
331  * stop it from freeing everything if there are other threads still running.
332  */
333 int
334 Perl_ithread_hook(pTHX)
335 {
336     dMY_POOL;
337     return ((aTHX == MY_POOL.main_thread.interp) ? S_exit_warning(aTHX) : 0);
338 }
339
340
341 /* MAGIC (in mg.h sense) hooks */
342
343 int
344 ithread_mg_get(pTHX_ SV *sv, MAGIC *mg)
345 {
346     ithread *thread = (ithread *)mg->mg_ptr;
347     SvIV_set(sv, PTR2IV(thread));
348     SvIOK_on(sv);
349     return (0);
350 }
351
352 int
353 ithread_mg_free(pTHX_ SV *sv, MAGIC *mg)
354 {
355     ithread *thread = (ithread *)mg->mg_ptr;
356     MUTEX_LOCK(&thread->mutex);
357     S_ithread_free(aTHX_ thread);   /* Releases MUTEX */
358     return (0);
359 }
360
361 int
362 ithread_mg_dup(pTHX_ MAGIC *mg, CLONE_PARAMS *param)
363 {
364     S_ithread_count_inc(aTHX_ (ithread *)mg->mg_ptr);
365     return (0);
366 }
367
368 MGVTBL ithread_vtbl = {
369     ithread_mg_get,     /* get */
370     0,                  /* set */
371     0,                  /* len */
372     0,                  /* clear */
373     ithread_mg_free,    /* free */
374     0,                  /* copy */
375     ithread_mg_dup      /* dup */
376 };
377
378
379 /* Provided default, minimum and rational stack sizes */
380 STATIC IV
381 S_good_stack_size(pTHX_ IV stack_size)
382 {
383     dMY_POOL;
384
385     /* Use default stack size if no stack size specified */
386     if (! stack_size) {
387         return (MY_POOL.default_stack_size);
388     }
389
390 #ifdef PTHREAD_STACK_MIN
391     /* Can't use less than minimum */
392     if (stack_size < PTHREAD_STACK_MIN) {
393         if (ckWARN(WARN_THREADS)) {
394             Perl_warn(aTHX_ "Using minimum thread stack size of %" IVdf, (IV)PTHREAD_STACK_MIN);
395         }
396         return (PTHREAD_STACK_MIN);
397     }
398 #endif
399
400     /* Round up to page size boundary */
401     if (MY_POOL.page_size <= 0) {
402 #if defined(HAS_SYSCONF) && (defined(_SC_PAGESIZE) || defined(_SC_MMAP_PAGE_SIZE))
403         SETERRNO(0, SS_NORMAL);
404 #  ifdef _SC_PAGESIZE
405         MY_POOL.page_size = sysconf(_SC_PAGESIZE);
406 #  else
407         MY_POOL.page_size = sysconf(_SC_MMAP_PAGE_SIZE);
408 #  endif
409         if ((long)MY_POOL.page_size < 0) {
410             if (errno) {
411                 SV * const error = get_sv("@", 0);
412                 (void)SvUPGRADE(error, SVt_PV);
413                 Perl_croak(aTHX_ "PANIC: sysconf: %s", SvPV_nolen(error));
414             } else {
415                 Perl_croak(aTHX_ "PANIC: sysconf: pagesize unknown");
416             }
417         }
418 #else
419 #  ifdef HAS_GETPAGESIZE
420         MY_POOL.page_size = getpagesize();
421 #  else
422 #    if defined(I_SYS_PARAM) && defined(PAGESIZE)
423         MY_POOL.page_size = PAGESIZE;
424 #    else
425         MY_POOL.page_size = 8192;   /* A conservative default */
426 #    endif
427 #  endif
428         if (MY_POOL.page_size <= 0) {
429             Perl_croak(aTHX_ "PANIC: bad pagesize %" IVdf, (IV)MY_POOL.page_size);
430         }
431 #endif
432     }
433     stack_size = ((stack_size + (MY_POOL.page_size - 1)) / MY_POOL.page_size) * MY_POOL.page_size;
434
435     return (stack_size);
436 }
437
438
439 /* Starts executing the thread.
440  * Passed as the C level function to run in the new thread.
441  */
442 #ifdef WIN32
443 STATIC THREAD_RET_TYPE
444 S_ithread_run(LPVOID arg)
445 #else
446 STATIC void *
447 S_ithread_run(void * arg)
448 #endif
449 {
450     ithread *thread = (ithread *)arg;
451     int jmp_rc = 0;
452     I32 oldscope;
453     int exit_app = 0;   /* Thread terminated using 'exit' */
454     int exit_code = 0;
455     int died = 0;       /* Thread terminated abnormally */
456
457     dJMPENV;
458
459     dTHXa(thread->interp);
460
461     dMY_POOL;
462
463     /* Blocked until ->create() call finishes */
464     MUTEX_LOCK(&thread->mutex);
465     MUTEX_UNLOCK(&thread->mutex);
466
467     PERL_SET_CONTEXT(thread->interp);
468     S_ithread_set(aTHX_ thread);
469
470     /* Thread starts with most signals blocked - restore the signal mask from
471      * the ithread struct.
472      */
473     S_set_sigmask(&thread->initial_sigmask);
474
475     PL_perl_destruct_level = 2;
476
477     {
478         AV *params = (AV *)SvRV(thread->params);
479         int len = (int)av_len(params)+1;
480         int ii;
481
482         dSP;
483         ENTER;
484         SAVETMPS;
485
486         /* Put args on the stack */
487         PUSHMARK(SP);
488         for (ii=0; ii < len; ii++) {
489             XPUSHs(av_shift(params));
490         }
491         PUTBACK;
492
493         oldscope = PL_scopestack_ix;
494         JMPENV_PUSH(jmp_rc);
495         if (jmp_rc == 0) {
496             /* Run the specified function */
497             len = (int)call_sv(thread->init_function, thread->gimme|G_EVAL);
498         } else if (jmp_rc == 2) {
499             /* Thread exited */
500             exit_app = 1;
501             exit_code = STATUS_CURRENT;
502             while (PL_scopestack_ix > oldscope) {
503                 LEAVE;
504             }
505         }
506         JMPENV_POP;
507
508         /* The interpreter is finished, so this thread can stop receiving
509          * signals.  This way, our signal handler doesn't get called in the
510          * middle of our parent thread calling perl_destruct()...
511          */
512         S_block_most_signals(NULL);
513
514         /* Remove args from stack and put back in params array */
515         SPAGAIN;
516         for (ii=len-1; ii >= 0; ii--) {
517             SV *sv = POPs;
518             if (jmp_rc == 0 && (thread->gimme & G_WANT) != G_VOID) {
519                 av_store(params, ii, SvREFCNT_inc(sv));
520             }
521         }
522
523         FREETMPS;
524         LEAVE;
525
526         /* Check for abnormal termination */
527         if (SvTRUE(ERRSV)) {
528             died = PERL_ITHR_DIED;
529             thread->err = newSVsv(ERRSV);
530             /* If ERRSV is an object, remember the classname and then
531              * rebless into 'main' so it will survive 'cloning'
532              */
533             if (sv_isobject(thread->err)) {
534                 thread->err_class = HvNAME(SvSTASH(SvRV(thread->err)));
535                 sv_bless(thread->err, gv_stashpv("main", 0));
536             }
537
538             if (ckWARN_d(WARN_THREADS)) {
539                 oldscope = PL_scopestack_ix;
540                 JMPENV_PUSH(jmp_rc);
541                 if (jmp_rc == 0) {
542                     /* Warn that thread died */
543                     Perl_warn(aTHX_ "Thread %" UVuf " terminated abnormally: %" SVf, thread->tid, ERRSV);
544                 } else if (jmp_rc == 2) {
545                     /* Warn handler exited */
546                     exit_app = 1;
547                     exit_code = STATUS_CURRENT;
548                     while (PL_scopestack_ix > oldscope) {
549                         LEAVE;
550                     }
551                 }
552                 JMPENV_POP;
553             }
554         }
555
556         /* Release function ref */
557         SvREFCNT_dec(thread->init_function);
558         thread->init_function = Nullsv;
559     }
560
561     PerlIO_flush((PerlIO *)NULL);
562
563     MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
564     MUTEX_LOCK(&thread->mutex);
565     /* Mark as finished */
566     thread->state |= (PERL_ITHR_FINISHED | died);
567     /* Clear exit flag if required */
568     if (thread->state & PERL_ITHR_THREAD_EXIT_ONLY) {
569         exit_app = 0;
570     }
571
572     /* Adjust thread status counts */
573     if (thread->state & PERL_ITHR_DETACHED) {
574         MY_POOL.detached_threads--;
575     } else {
576         MY_POOL.running_threads--;
577         MY_POOL.joinable_threads++;
578     }
579     MUTEX_UNLOCK(&thread->mutex);
580     MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
581
582     /* Exit application if required */
583     if (exit_app) {
584         oldscope = PL_scopestack_ix;
585         JMPENV_PUSH(jmp_rc);
586         if (jmp_rc == 0) {
587             /* Warn if there are unjoined threads */
588             S_exit_warning(aTHX);
589         } else if (jmp_rc == 2) {
590             /* Warn handler exited */
591             exit_code = STATUS_CURRENT;
592             while (PL_scopestack_ix > oldscope) {
593                 LEAVE;
594             }
595         }
596         JMPENV_POP;
597
598         my_exit(exit_code);
599     }
600
601     /* At this point, the interpreter may have been freed, so call
602      * free in the the context of of the 'main' interpreter which
603      * can't have been freed due to the veto_cleanup mechanism.
604      */
605     aTHX = MY_POOL.main_thread.interp;
606
607     MUTEX_LOCK(&thread->mutex);
608     S_ithread_free(aTHX_ thread);   /* Releases MUTEX */
609
610 #ifdef WIN32
611     return ((DWORD)0);
612 #else
613     return (0);
614 #endif
615 }
616
617
618 /* Type conversion helper functions */
619
620 STATIC SV *
621 S_ithread_to_SV(pTHX_ SV *obj, ithread *thread, char *classname, bool inc)
622 {
623     SV *sv;
624     MAGIC *mg;
625
626     if (inc)
627         S_ithread_count_inc(aTHX_ thread);
628
629     if (! obj) {
630         obj = newSV(0);
631     }
632
633     sv = newSVrv(obj, classname);
634     sv_setiv(sv, PTR2IV(thread));
635     mg = sv_magicext(sv, Nullsv, PERL_MAGIC_shared_scalar, &ithread_vtbl, (char *)thread, 0);
636     mg->mg_flags |= MGf_DUP;
637     SvREADONLY_on(sv);
638
639     return (obj);
640 }
641
642 STATIC ithread *
643 S_SV_to_ithread(pTHX_ SV *sv)
644 {
645     /* Argument is a thread */
646     if (SvROK(sv)) {
647       return (INT2PTR(ithread *, SvIV(SvRV(sv))));
648     }
649     /* Argument is classname, therefore return current thread */
650     return (S_ithread_get(aTHX));
651 }
652
653
654 /* threads->create()
655  * Called in context of parent thread.
656  * Called with MY_POOL.create_destruct_mutex locked.  (Unlocked on error.)
657  */
658 STATIC ithread *
659 S_ithread_create(
660         pTHX_ SV *init_function,
661         IV        stack_size,
662         int       gimme,
663         int       exit_opt,
664         SV       *params)
665 {
666     ithread     *thread;
667     ithread     *current_thread = S_ithread_get(aTHX);
668
669     SV         **tmps_tmp = PL_tmps_stack;
670     IV           tmps_ix  = PL_tmps_ix;
671 #ifndef WIN32
672     int          rc_stack_size = 0;
673     int          rc_thread_create = 0;
674 #endif
675     dMY_POOL;
676
677     /* Allocate thread structure in context of the main thread's interpreter */
678     {
679         PERL_SET_CONTEXT(MY_POOL.main_thread.interp);
680         thread = (ithread *)PerlMemShared_malloc(sizeof(ithread));
681     }
682     PERL_SET_CONTEXT(aTHX);
683     if (!thread) {
684         MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
685         PerlLIO_write(PerlIO_fileno(Perl_error_log), PL_no_mem, strlen(PL_no_mem));
686         my_exit(1);
687     }
688     Zero(thread, 1, ithread);
689
690     /* Add to threads list */
691     thread->next = &MY_POOL.main_thread;
692     thread->prev = MY_POOL.main_thread.prev;
693     MY_POOL.main_thread.prev = thread;
694     thread->prev->next = thread;
695     MY_POOL.total_threads++;
696
697     /* 1 ref to be held by the local var 'thread' in S_ithread_run().
698      * 1 ref to be held by the threads object that we assume we will
699      *      be embedded in upon our return.
700      * 1 ref to be the responsibility of join/detach, so we don't get
701      *      freed until join/detach, even if no thread objects remain.
702      *      This allows the following to work:
703      *          { threads->create(sub{...}); } threads->object(1)->join;
704      */
705     thread->count = 3;
706
707     /* Block new thread until ->create() call finishes */
708     MUTEX_INIT(&thread->mutex);
709     MUTEX_LOCK(&thread->mutex);
710
711     thread->tid = MY_POOL.tid_counter++;
712     thread->stack_size = S_good_stack_size(aTHX_ stack_size);
713     thread->gimme = gimme;
714     thread->state = exit_opt;
715
716     /* "Clone" our interpreter into the thread's interpreter.
717      * This gives thread access to "static data" and code.
718      */
719     PerlIO_flush((PerlIO *)NULL);
720     S_ithread_set(aTHX_ thread);
721
722     SAVEBOOL(PL_srand_called); /* Save this so it becomes the correct value */
723     PL_srand_called = FALSE;   /* Set it to false so we can detect if it gets
724                                   set during the clone */
725
726     /* perl_clone() will leave us the new interpreter's context.  This poses
727      * two problems for our signal handler.  First, it sets the new context
728      * before the new interpreter struct is fully initialized, so our signal
729      * handler might find bogus data in the interpreter struct it gets.
730      * Second, even if the interpreter is initialized before a signal comes in,
731      * we would like to avoid that interpreter receiving notifications for
732      * signals (especially when they ought to be for the one running in this
733      * thread), until it is running in its own thread.  Another problem is that
734      * the new thread will not have set the context until some time after it
735      * has started, so it won't be safe for our signal handler to run until
736      * that time.
737      *
738      * So we block most signals here, so the new thread will inherit the signal
739      * mask, and unblock them right after the thread creation.  The original
740      * mask is saved in the thread struct so that the new thread can restore
741      * the original mask.
742      */
743     S_block_most_signals(&thread->initial_sigmask);
744
745 #ifdef WIN32
746     thread->interp = perl_clone(aTHX, CLONEf_KEEP_PTR_TABLE | CLONEf_CLONE_HOST);
747 #else
748     thread->interp = perl_clone(aTHX, CLONEf_KEEP_PTR_TABLE);
749 #endif
750
751     /* perl_clone() leaves us in new interpreter's context.  As it is tricky
752      * to spot an implicit aTHX, create a new scope with aTHX matching the
753      * context for the duration of our work for new interpreter.
754      */
755     {
756         CLONE_PARAMS clone_param;
757
758         dTHXa(thread->interp);
759
760         MY_CXT_CLONE;
761
762         /* Here we remove END blocks since they should only run in the thread
763          * they are created
764          */
765         SvREFCNT_dec(PL_endav);
766         PL_endav = newAV();
767
768         clone_param.flags = 0;
769         if (SvPOK(init_function)) {
770             thread->init_function = newSV(0);
771             sv_copypv(thread->init_function, init_function);
772         } else {
773             thread->init_function =
774                 SvREFCNT_inc(sv_dup(init_function, &clone_param));
775         }
776
777         thread->params = sv_dup(params, &clone_param);
778         SvREFCNT_inc_void(thread->params);
779
780         /* The code below checks that anything living on the tmps stack and
781          * has been cloned (so it lives in the ptr_table) has a refcount
782          * higher than 0.
783          *
784          * If the refcount is 0 it means that a something on the stack/context
785          * was holding a reference to it and since we init_stacks() in
786          * perl_clone that won't get cleaned and we will get a leaked scalar.
787          * The reason it was cloned was that it lived on the @_ stack.
788          *
789          * Example of this can be found in bugreport 15837 where calls in the
790          * parameter list end up as a temp.
791          *
792          * One could argue that this fix should be in perl_clone.
793          */
794         while (tmps_ix > 0) {
795             SV* sv = (SV*)ptr_table_fetch(PL_ptr_table, tmps_tmp[tmps_ix]);
796             tmps_ix--;
797             if (sv && SvREFCNT(sv) == 0) {
798                 SvREFCNT_inc_void(sv);
799                 SvREFCNT_dec(sv);
800             }
801         }
802
803         SvTEMP_off(thread->init_function);
804         ptr_table_free(PL_ptr_table);
805         PL_ptr_table = NULL;
806         PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
807     }
808     S_ithread_set(aTHX_ current_thread);
809     PERL_SET_CONTEXT(aTHX);
810
811     /* Create/start the thread */
812 #ifdef WIN32
813     thread->handle = CreateThread(NULL,
814                                   (DWORD)thread->stack_size,
815                                   S_ithread_run,
816                                   (LPVOID)thread,
817                                   STACK_SIZE_PARAM_IS_A_RESERVATION,
818                                   &thread->thr);
819 #else
820     {
821         STATIC pthread_attr_t attr;
822         STATIC int attr_inited = 0;
823         STATIC int attr_joinable = PTHREAD_CREATE_JOINABLE;
824         if (! attr_inited) {
825             pthread_attr_init(&attr);
826             attr_inited = 1;
827         }
828
829 #  ifdef PTHREAD_ATTR_SETDETACHSTATE
830         /* Threads start out joinable */
831         PTHREAD_ATTR_SETDETACHSTATE(&attr, attr_joinable);
832 #  endif
833
834 #  ifdef _POSIX_THREAD_ATTR_STACKSIZE
835         /* Set thread's stack size */
836         if (thread->stack_size > 0) {
837             rc_stack_size = pthread_attr_setstacksize(&attr, (size_t)thread->stack_size);
838         }
839 #  endif
840
841         /* Create the thread */
842         if (! rc_stack_size) {
843 #  ifdef OLD_PTHREADS_API
844             rc_thread_create = pthread_create(&thread->thr,
845                                               attr,
846                                               S_ithread_run,
847                                               (void *)thread);
848 #  else
849 #    if defined(HAS_PTHREAD_ATTR_SETSCOPE) && defined(PTHREAD_SCOPE_SYSTEM)
850             pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);
851 #    endif
852             rc_thread_create = pthread_create(&thread->thr,
853                                               &attr,
854                                               S_ithread_run,
855                                               (void *)thread);
856 #  endif
857         }
858
859     /* Now it's safe to accept signals, since we're in our own interpreter's
860      * context and we have created the thread.
861      */
862     S_set_sigmask(&thread->initial_sigmask);
863
864 #  ifdef _POSIX_THREAD_ATTR_STACKSIZE
865         /* Try to get thread's actual stack size */
866         {
867             size_t stacksize;
868 #ifdef HPUX1020
869             stacksize = pthread_attr_getstacksize(attr);
870 #else
871             if (! pthread_attr_getstacksize(&attr, &stacksize))
872 #endif
873                 if (stacksize > 0) {
874                     thread->stack_size = (IV)stacksize;
875                 }
876         }
877 #  endif
878     }
879 #endif
880
881     /* Check for errors */
882 #ifdef WIN32
883     if (thread->handle == NULL) {
884 #else
885     if (rc_stack_size || rc_thread_create) {
886 #endif
887         /* Must unlock mutex for destruct call */
888         MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
889         sv_2mortal(params);
890         thread->state |= PERL_ITHR_NONVIABLE;
891         S_ithread_free(aTHX_ thread);   /* Releases MUTEX */
892 #ifndef WIN32
893         if (ckWARN_d(WARN_THREADS)) {
894             if (rc_stack_size) {
895                 Perl_warn(aTHX_ "Thread creation failed: pthread_attr_setstacksize(%" IVdf ") returned %d", thread->stack_size, rc_stack_size);
896             } else {
897                 Perl_warn(aTHX_ "Thread creation failed: pthread_create returned %d", rc_thread_create);
898             }
899         }
900 #endif
901         return (NULL);
902     }
903
904     MY_POOL.running_threads++;
905     sv_2mortal(params);
906     return (thread);
907 }
908
909 #endif /* USE_ITHREADS */
910
911
912 MODULE = threads    PACKAGE = threads    PREFIX = ithread_
913 PROTOTYPES: DISABLE
914
915 #ifdef USE_ITHREADS
916
917 void
918 ithread_create(...)
919     PREINIT:
920         char *classname;
921         ithread *thread;
922         SV *function_to_call;
923         AV *params;
924         HV *specs;
925         IV stack_size;
926         int context;
927         int exit_opt;
928         SV *thread_exit_only;
929         char *str;
930         int idx;
931         int ii;
932         dMY_POOL;
933     CODE:
934         if ((items >= 2) && SvROK(ST(1)) && SvTYPE(SvRV(ST(1)))==SVt_PVHV) {
935             if (--items < 2) {
936                 Perl_croak(aTHX_ "Usage: threads->create(\\%%specs, function, ...)");
937             }
938             specs = (HV*)SvRV(ST(1));
939             idx = 1;
940         } else {
941             if (items < 2) {
942                 Perl_croak(aTHX_ "Usage: threads->create(function, ...)");
943             }
944             specs = NULL;
945             idx = 0;
946         }
947
948         if (sv_isobject(ST(0))) {
949             /* $thr->create() */
950             classname = HvNAME(SvSTASH(SvRV(ST(0))));
951             thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
952             MUTEX_LOCK(&thread->mutex);
953             stack_size = thread->stack_size;
954             exit_opt = thread->state & PERL_ITHR_THREAD_EXIT_ONLY;
955             MUTEX_UNLOCK(&thread->mutex);
956         } else {
957             /* threads->create() */
958             classname = (char *)SvPV_nolen(ST(0));
959             stack_size = MY_POOL.default_stack_size;
960             thread_exit_only = get_sv("threads::thread_exit_only", GV_ADD);
961             exit_opt = (SvTRUE(thread_exit_only))
962                                     ? PERL_ITHR_THREAD_EXIT_ONLY : 0;
963         }
964
965         function_to_call = ST(idx+1);
966
967         context = -1;
968         if (specs) {
969             /* stack_size */
970             if (hv_exists(specs, "stack", 5)) {
971                 stack_size = SvIV(*hv_fetch(specs, "stack", 5, 0));
972             } else if (hv_exists(specs, "stacksize", 9)) {
973                 stack_size = SvIV(*hv_fetch(specs, "stacksize", 9, 0));
974             } else if (hv_exists(specs, "stack_size", 10)) {
975                 stack_size = SvIV(*hv_fetch(specs, "stack_size", 10, 0));
976             }
977
978             /* context */
979             if (hv_exists(specs, "context", 7)) {
980                 str = (char *)SvPV_nolen(*hv_fetch(specs, "context", 7, 0));
981                 switch (*str) {
982                     case 'a':
983                     case 'A':
984                     case 'l':
985                     case 'L':
986                         context = G_ARRAY;
987                         break;
988                     case 's':
989                     case 'S':
990                         context = G_SCALAR;
991                         break;
992                     case 'v':
993                     case 'V':
994                         context = G_VOID;
995                         break;
996                     default:
997                         Perl_croak(aTHX_ "Invalid context: %s", str);
998                 }
999             } else if (hv_exists(specs, "array", 5)) {
1000                 if (SvTRUE(*hv_fetch(specs, "array", 5, 0))) {
1001                     context = G_ARRAY;
1002                 }
1003             } else if (hv_exists(specs, "list", 4)) {
1004                 if (SvTRUE(*hv_fetch(specs, "list", 4, 0))) {
1005                     context = G_ARRAY;
1006                 }
1007             } else if (hv_exists(specs, "scalar", 6)) {
1008                 if (SvTRUE(*hv_fetch(specs, "scalar", 6, 0))) {
1009                     context = G_SCALAR;
1010                 }
1011             } else if (hv_exists(specs, "void", 4)) {
1012                 if (SvTRUE(*hv_fetch(specs, "void", 4, 0))) {
1013                     context = G_VOID;
1014                 }
1015             }
1016
1017             /* exit => thread_only */
1018             if (hv_exists(specs, "exit", 4)) {
1019                 str = (char *)SvPV_nolen(*hv_fetch(specs, "exit", 4, 0));
1020                 exit_opt = (*str == 't' || *str == 'T')
1021                                     ? PERL_ITHR_THREAD_EXIT_ONLY : 0;
1022             }
1023         }
1024         if (context == -1) {
1025             context = GIMME_V;  /* Implicit context */
1026         } else {
1027             context |= (GIMME_V & (~(G_ARRAY|G_SCALAR|G_VOID)));
1028         }
1029
1030         /* Function args */
1031         params = newAV();
1032         if (items > 2) {
1033             for (ii=2; ii < items ; ii++) {
1034                 av_push(params, SvREFCNT_inc(ST(idx+ii)));
1035             }
1036         }
1037
1038         /* Create thread */
1039         MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
1040         thread = S_ithread_create(aTHX_ function_to_call,
1041                                         stack_size,
1042                                         context,
1043                                         exit_opt,
1044                                         newRV_noinc((SV*)params));
1045         if (! thread) {
1046             XSRETURN_UNDEF;     /* Mutex already unlocked */
1047         }
1048         ST(0) = sv_2mortal(S_ithread_to_SV(aTHX_ Nullsv, thread, classname, FALSE));
1049         MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
1050
1051         /* Let thread run */
1052         MUTEX_UNLOCK(&thread->mutex);
1053
1054         /* XSRETURN(1); - implied */
1055
1056
1057 void
1058 ithread_list(...)
1059     PREINIT:
1060         char *classname;
1061         ithread *thread;
1062         int list_context;
1063         IV count = 0;
1064         int want_running = 0;
1065         int state;
1066         dMY_POOL;
1067     PPCODE:
1068         /* Class method only */
1069         if (SvROK(ST(0))) {
1070             Perl_croak(aTHX_ "Usage: threads->list(...)");
1071         }
1072         classname = (char *)SvPV_nolen(ST(0));
1073
1074         /* Calling context */
1075         list_context = (GIMME_V == G_ARRAY);
1076
1077         /* Running or joinable parameter */
1078         if (items > 1) {
1079             want_running = SvTRUE(ST(1));
1080         }
1081
1082         /* Walk through threads list */
1083         MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
1084         for (thread = MY_POOL.main_thread.next;
1085              thread != &MY_POOL.main_thread;
1086              thread = thread->next)
1087         {
1088             MUTEX_LOCK(&thread->mutex);
1089             state = thread->state;
1090             MUTEX_UNLOCK(&thread->mutex);
1091
1092             /* Ignore detached or joined threads */
1093             if (state & PERL_ITHR_UNCALLABLE) {
1094                 continue;
1095             }
1096
1097             /* Filter per parameter */
1098             if (items > 1) {
1099                 if (want_running) {
1100                     if (state & PERL_ITHR_FINISHED) {
1101                         continue;   /* Not running */
1102                     }
1103                 } else {
1104                     if (! (state & PERL_ITHR_FINISHED)) {
1105                         continue;   /* Still running - not joinable yet */
1106                     }
1107                 }
1108             }
1109
1110             /* Push object on stack if list context */
1111             if (list_context) {
1112                 XPUSHs(sv_2mortal(S_ithread_to_SV(aTHX_ Nullsv, thread, classname, TRUE)));
1113             }
1114             count++;
1115         }
1116         MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
1117         /* If scalar context, send back count */
1118         if (! list_context) {
1119             XSRETURN_IV(count);
1120         }
1121
1122
1123 void
1124 ithread_self(...)
1125     PREINIT:
1126         char *classname;
1127         ithread *thread;
1128     CODE:
1129         /* Class method only */
1130         if ((items != 1) || SvROK(ST(0))) {
1131             Perl_croak(aTHX_ "Usage: threads->self()");
1132         }
1133         classname = (char *)SvPV_nolen(ST(0));
1134
1135         thread = S_ithread_get(aTHX);
1136
1137         ST(0) = sv_2mortal(S_ithread_to_SV(aTHX_ Nullsv, thread, classname, TRUE));
1138         /* XSRETURN(1); - implied */
1139
1140
1141 void
1142 ithread_tid(...)
1143     PREINIT:
1144         ithread *thread;
1145     CODE:
1146         PERL_UNUSED_VAR(items);
1147         thread = S_SV_to_ithread(aTHX_ ST(0));
1148         XST_mUV(0, thread->tid);
1149         /* XSRETURN(1); - implied */
1150
1151
1152 void
1153 ithread_join(...)
1154     PREINIT:
1155         ithread *thread;
1156         ithread *current_thread;
1157         int join_err;
1158         AV *params = NULL;
1159         int len;
1160         int ii;
1161 #ifndef WIN32
1162         int rc_join;
1163         void *retval;
1164 #endif
1165         dMY_POOL;
1166     PPCODE:
1167         /* Object method only */
1168         if ((items != 1) || ! sv_isobject(ST(0))) {
1169             Perl_croak(aTHX_ "Usage: $thr->join()");
1170         }
1171
1172         /* Check if the thread is joinable and not ourselves */
1173         thread = S_SV_to_ithread(aTHX_ ST(0));
1174         current_thread = S_ithread_get(aTHX);
1175
1176         MUTEX_LOCK(&thread->mutex);
1177         if ((join_err = (thread->state & PERL_ITHR_UNCALLABLE))) {
1178             MUTEX_UNLOCK(&thread->mutex);
1179             Perl_croak(aTHX_ (join_err & PERL_ITHR_DETACHED)
1180                                 ? "Cannot join a detached thread"
1181                                 : "Thread already joined");
1182         } else if (thread->tid == current_thread->tid) {
1183             MUTEX_UNLOCK(&thread->mutex);
1184             Perl_croak(aTHX_ "Cannot join self");
1185         }
1186
1187         /* Mark as joined */
1188         thread->state |= PERL_ITHR_JOINED;
1189         MUTEX_UNLOCK(&thread->mutex);
1190
1191         MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
1192         MY_POOL.joinable_threads--;
1193         MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
1194
1195         /* Join the thread */
1196 #ifdef WIN32
1197         if (WaitForSingleObject(thread->handle, INFINITE) != WAIT_OBJECT_0) {
1198             /* Timeout/abandonment unexpected here; check $^E */
1199             Perl_croak(aTHX_ "PANIC: underlying join failed");
1200         };
1201 #else
1202         if ((rc_join = pthread_join(thread->thr, &retval)) != 0) {
1203             /* In progress/deadlock/unknown unexpected here; check $! */
1204             errno = rc_join;
1205             Perl_croak(aTHX_ "PANIC: underlying join failed");
1206         };
1207 #endif
1208
1209         MUTEX_LOCK(&thread->mutex);
1210         /* Get the return value from the call_sv */
1211         /* Objects do not survive this process - FIXME */
1212         if ((thread->gimme & G_WANT) != G_VOID) {
1213             AV *params_copy;
1214             PerlInterpreter *other_perl;
1215             CLONE_PARAMS clone_params;
1216
1217             params_copy = (AV *)SvRV(thread->params);
1218             other_perl = thread->interp;
1219             clone_params.stashes = newAV();
1220             clone_params.flags = CLONEf_JOIN_IN;
1221             PL_ptr_table = ptr_table_new();
1222             S_ithread_set(aTHX_ thread);
1223             /* Ensure 'meaningful' addresses retain their meaning */
1224             ptr_table_store(PL_ptr_table, &other_perl->Isv_undef, &PL_sv_undef);
1225             ptr_table_store(PL_ptr_table, &other_perl->Isv_no, &PL_sv_no);
1226             ptr_table_store(PL_ptr_table, &other_perl->Isv_yes, &PL_sv_yes);
1227             params = (AV *)sv_dup((SV*)params_copy, &clone_params);
1228             S_ithread_set(aTHX_ current_thread);
1229             SvREFCNT_dec(clone_params.stashes);
1230             SvREFCNT_inc_void(params);
1231             ptr_table_free(PL_ptr_table);
1232             PL_ptr_table = NULL;
1233         }
1234
1235         /* If thread didn't die, then we can free its interpreter */
1236         if (! (thread->state & PERL_ITHR_DIED)) {
1237             S_ithread_clear(aTHX_ thread);
1238         }
1239         S_ithread_free(aTHX_ thread);   /* Releases MUTEX */
1240
1241         /* If no return values, then just return */
1242         if (! params) {
1243             XSRETURN_UNDEF;
1244         }
1245
1246         /* Put return values on stack */
1247         len = (int)AvFILL(params);
1248         for (ii=0; ii <= len; ii++) {
1249             SV* param = av_shift(params);
1250             XPUSHs(sv_2mortal(param));
1251         }
1252
1253         /* Free return value array */
1254         SvREFCNT_dec(params);
1255
1256
1257 void
1258 ithread_yield(...)
1259     CODE:
1260         PERL_UNUSED_VAR(items);
1261         YIELD;
1262
1263
1264 void
1265 ithread_detach(...)
1266     PREINIT:
1267         ithread *thread;
1268         int detach_err;
1269         dMY_POOL;
1270     CODE:
1271         PERL_UNUSED_VAR(items);
1272
1273         /* Detach the thread */
1274         thread = S_SV_to_ithread(aTHX_ ST(0));
1275         MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
1276         MUTEX_LOCK(&thread->mutex);
1277         if (! (detach_err = (thread->state & PERL_ITHR_UNCALLABLE))) {
1278             /* Thread is detachable */
1279             thread->state |= PERL_ITHR_DETACHED;
1280 #ifdef WIN32
1281             /* Windows has no 'detach thread' function */
1282 #else
1283             PERL_THREAD_DETACH(thread->thr);
1284 #endif
1285             if (thread->state & PERL_ITHR_FINISHED) {
1286                 MY_POOL.joinable_threads--;
1287             } else {
1288                 MY_POOL.running_threads--;
1289                 MY_POOL.detached_threads++;
1290             }
1291         }
1292         MUTEX_UNLOCK(&thread->mutex);
1293         MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
1294
1295         if (detach_err) {
1296             Perl_croak(aTHX_ (detach_err & PERL_ITHR_DETACHED)
1297                                 ? "Thread already detached"
1298                                 : "Cannot detach a joined thread");
1299         }
1300
1301         /* If thread is finished and didn't die,
1302          * then we can free its interpreter */
1303         MUTEX_LOCK(&thread->mutex);
1304         if ((thread->state & PERL_ITHR_FINISHED) &&
1305             ! (thread->state & PERL_ITHR_DIED))
1306         {
1307             S_ithread_clear(aTHX_ thread);
1308         }
1309         S_ithread_free(aTHX_ thread);   /* Releases MUTEX */
1310
1311
1312 void
1313 ithread_kill(...)
1314     PREINIT:
1315         ithread *thread;
1316         char *sig_name;
1317         IV signal;
1318     CODE:
1319         /* Must have safe signals */
1320         if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG) {
1321             Perl_croak(aTHX_ "Cannot signal threads without safe signals");
1322         }
1323
1324         /* Object method only */
1325         if ((items != 2) || ! sv_isobject(ST(0))) {
1326             Perl_croak(aTHX_ "Usage: $thr->kill('SIG...')");
1327         }
1328
1329         /* Get signal */
1330         sig_name = SvPV_nolen(ST(1));
1331         if (isALPHA(*sig_name)) {
1332             if (*sig_name == 'S' && sig_name[1] == 'I' && sig_name[2] == 'G') {
1333                 sig_name += 3;
1334             }
1335             if ((signal = whichsig(sig_name)) < 0) {
1336                 Perl_croak(aTHX_ "Unrecognized signal name: %s", sig_name);
1337             }
1338         } else {
1339             signal = SvIV(ST(1));
1340         }
1341
1342         /* Set the signal for the thread */
1343         thread = S_SV_to_ithread(aTHX_ ST(0));
1344         MUTEX_LOCK(&thread->mutex);
1345         if (thread->interp) {
1346             dTHXa(thread->interp);
1347             PL_psig_pend[signal]++;
1348             PL_sig_pending = 1;
1349         }
1350         MUTEX_UNLOCK(&thread->mutex);
1351
1352         /* Return the thread to allow for method chaining */
1353         ST(0) = ST(0);
1354         /* XSRETURN(1); - implied */
1355
1356
1357 void
1358 ithread_DESTROY(...)
1359     CODE:
1360         PERL_UNUSED_VAR(items);
1361         sv_unmagic(SvRV(ST(0)), PERL_MAGIC_shared_scalar);
1362
1363
1364 void
1365 ithread_equal(...)
1366     PREINIT:
1367         int are_equal = 0;
1368     CODE:
1369         PERL_UNUSED_VAR(items);
1370
1371         /* Compares TIDs to determine thread equality */
1372         if (sv_isobject(ST(0)) && sv_isobject(ST(1))) {
1373             ithread *thr1 = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1374             ithread *thr2 = INT2PTR(ithread *, SvIV(SvRV(ST(1))));
1375             are_equal = (thr1->tid == thr2->tid);
1376         }
1377         if (are_equal) {
1378             XST_mYES(0);
1379         } else {
1380             /* Return 0 on false for backward compatibility */
1381             XST_mIV(0, 0);
1382         }
1383         /* XSRETURN(1); - implied */
1384
1385
1386 void
1387 ithread_object(...)
1388     PREINIT:
1389         char *classname;
1390         UV tid;
1391         ithread *thread;
1392         int state;
1393         int have_obj = 0;
1394         dMY_POOL;
1395     CODE:
1396         /* Class method only */
1397         if (SvROK(ST(0))) {
1398             Perl_croak(aTHX_ "Usage: threads->object($tid)");
1399         }
1400         classname = (char *)SvPV_nolen(ST(0));
1401
1402         if ((items < 2) || ! SvOK(ST(1))) {
1403             XSRETURN_UNDEF;
1404         }
1405
1406         /* threads->object($tid) */
1407         tid = SvUV(ST(1));
1408
1409         /* Walk through threads list */
1410         MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
1411         for (thread = MY_POOL.main_thread.next;
1412              thread != &MY_POOL.main_thread;
1413              thread = thread->next)
1414         {
1415             /* Look for TID */
1416             if (thread->tid == tid) {
1417                 /* Ignore if detached or joined */
1418                 MUTEX_LOCK(&thread->mutex);
1419                 state = thread->state;
1420                 MUTEX_UNLOCK(&thread->mutex);
1421                 if (! (state & PERL_ITHR_UNCALLABLE)) {
1422                     /* Put object on stack */
1423                     ST(0) = sv_2mortal(S_ithread_to_SV(aTHX_ Nullsv, thread, classname, TRUE));
1424                     have_obj = 1;
1425                 }
1426                 break;
1427             }
1428         }
1429         MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
1430
1431         if (! have_obj) {
1432             XSRETURN_UNDEF;
1433         }
1434         /* XSRETURN(1); - implied */
1435
1436
1437 void
1438 ithread__handle(...);
1439     PREINIT:
1440         ithread *thread;
1441     CODE:
1442         PERL_UNUSED_VAR(items);
1443         thread = S_SV_to_ithread(aTHX_ ST(0));
1444 #ifdef WIN32
1445         XST_mUV(0, PTR2UV(&thread->handle));
1446 #else
1447         XST_mUV(0, PTR2UV(&thread->thr));
1448 #endif
1449         /* XSRETURN(1); - implied */
1450
1451
1452 void
1453 ithread_get_stack_size(...)
1454     PREINIT:
1455         IV stack_size;
1456         dMY_POOL;
1457     CODE:
1458         PERL_UNUSED_VAR(items);
1459         if (sv_isobject(ST(0))) {
1460             /* $thr->get_stack_size() */
1461             ithread *thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1462             stack_size = thread->stack_size;
1463         } else {
1464             /* threads->get_stack_size() */
1465             stack_size = MY_POOL.default_stack_size;
1466         }
1467         XST_mIV(0, stack_size);
1468         /* XSRETURN(1); - implied */
1469
1470
1471 void
1472 ithread_set_stack_size(...)
1473     PREINIT:
1474         IV old_size;
1475         dMY_POOL;
1476     CODE:
1477         if (items != 2) {
1478             Perl_croak(aTHX_ "Usage: threads->set_stack_size($size)");
1479         }
1480         if (sv_isobject(ST(0))) {
1481             Perl_croak(aTHX_ "Cannot change stack size of an existing thread");
1482         }
1483         if (! looks_like_number(ST(1))) {
1484             Perl_croak(aTHX_ "Stack size must be numeric");
1485         }
1486
1487         old_size = MY_POOL.default_stack_size;
1488         MY_POOL.default_stack_size = S_good_stack_size(aTHX_ SvIV(ST(1)));
1489         XST_mIV(0, old_size);
1490         /* XSRETURN(1); - implied */
1491
1492
1493 void
1494 ithread_is_running(...)
1495     PREINIT:
1496         ithread *thread;
1497     CODE:
1498         /* Object method only */
1499         if ((items != 1) || ! sv_isobject(ST(0))) {
1500             Perl_croak(aTHX_ "Usage: $thr->is_running()");
1501         }
1502
1503         thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1504         MUTEX_LOCK(&thread->mutex);
1505         ST(0) = (thread->state & PERL_ITHR_FINISHED) ? &PL_sv_no : &PL_sv_yes;
1506         MUTEX_UNLOCK(&thread->mutex);
1507         /* XSRETURN(1); - implied */
1508
1509
1510 void
1511 ithread_is_detached(...)
1512     PREINIT:
1513         ithread *thread;
1514     CODE:
1515         PERL_UNUSED_VAR(items);
1516         thread = S_SV_to_ithread(aTHX_ ST(0));
1517         MUTEX_LOCK(&thread->mutex);
1518         ST(0) = (thread->state & PERL_ITHR_DETACHED) ? &PL_sv_yes : &PL_sv_no;
1519         MUTEX_UNLOCK(&thread->mutex);
1520         /* XSRETURN(1); - implied */
1521
1522
1523 void
1524 ithread_is_joinable(...)
1525     PREINIT:
1526         ithread *thread;
1527     CODE:
1528         /* Object method only */
1529         if ((items != 1) || ! sv_isobject(ST(0))) {
1530             Perl_croak(aTHX_ "Usage: $thr->is_joinable()");
1531         }
1532
1533         thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1534         MUTEX_LOCK(&thread->mutex);
1535         ST(0) = ((thread->state & PERL_ITHR_FINISHED) &&
1536                  ! (thread->state & PERL_ITHR_UNCALLABLE))
1537             ? &PL_sv_yes : &PL_sv_no;
1538         MUTEX_UNLOCK(&thread->mutex);
1539         /* XSRETURN(1); - implied */
1540
1541
1542 void
1543 ithread_wantarray(...)
1544     PREINIT:
1545         ithread *thread;
1546     CODE:
1547         PERL_UNUSED_VAR(items);
1548         thread = S_SV_to_ithread(aTHX_ ST(0));
1549         ST(0) = ((thread->gimme & G_WANT) == G_ARRAY) ? &PL_sv_yes :
1550                 ((thread->gimme & G_WANT) == G_VOID)  ? &PL_sv_undef
1551                                        /* G_SCALAR */ : &PL_sv_no;
1552         /* XSRETURN(1); - implied */
1553
1554
1555 void
1556 ithread_set_thread_exit_only(...)
1557     PREINIT:
1558         ithread *thread;
1559     CODE:
1560         if (items != 2) {
1561             Perl_croak(aTHX_ "Usage: ->set_thread_exit_only(boolean)");
1562         }
1563         thread = S_SV_to_ithread(aTHX_ ST(0));
1564         MUTEX_LOCK(&thread->mutex);
1565         if (SvTRUE(ST(1))) {
1566             thread->state |= PERL_ITHR_THREAD_EXIT_ONLY;
1567         } else {
1568             thread->state &= ~PERL_ITHR_THREAD_EXIT_ONLY;
1569         }
1570         MUTEX_UNLOCK(&thread->mutex);
1571
1572
1573 void
1574 ithread_error(...)
1575     PREINIT:
1576         ithread *thread;
1577         SV *err = NULL;
1578     CODE:
1579         /* Object method only */
1580         if ((items != 1) || ! sv_isobject(ST(0))) {
1581             Perl_croak(aTHX_ "Usage: $thr->err()");
1582         }
1583
1584         thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1585         MUTEX_LOCK(&thread->mutex);
1586
1587         /* If thread died, then clone the error into the calling thread */
1588         if (thread->state & PERL_ITHR_DIED) {
1589             PerlInterpreter *other_perl;
1590             CLONE_PARAMS clone_params;
1591             ithread *current_thread;
1592
1593             other_perl = thread->interp;
1594             clone_params.stashes = newAV();
1595             clone_params.flags = CLONEf_JOIN_IN;
1596             PL_ptr_table = ptr_table_new();
1597             current_thread = S_ithread_get(aTHX);
1598             S_ithread_set(aTHX_ thread);
1599             /* Ensure 'meaningful' addresses retain their meaning */
1600             ptr_table_store(PL_ptr_table, &other_perl->Isv_undef, &PL_sv_undef);
1601             ptr_table_store(PL_ptr_table, &other_perl->Isv_no, &PL_sv_no);
1602             ptr_table_store(PL_ptr_table, &other_perl->Isv_yes, &PL_sv_yes);
1603             err = sv_dup(thread->err, &clone_params);
1604             S_ithread_set(aTHX_ current_thread);
1605             SvREFCNT_dec(clone_params.stashes);
1606             SvREFCNT_inc_void(err);
1607             /* If error was an object, bless it into the correct class */
1608             if (thread->err_class) {
1609                 sv_bless(err, gv_stashpv(thread->err_class, 1));
1610             }
1611             ptr_table_free(PL_ptr_table);
1612             PL_ptr_table = NULL;
1613         }
1614
1615         MUTEX_UNLOCK(&thread->mutex);
1616
1617         if (! err) {
1618             XSRETURN_UNDEF;
1619         }
1620
1621         ST(0) = sv_2mortal(err);
1622         /* XSRETURN(1); - implied */
1623
1624
1625 #endif /* USE_ITHREADS */
1626
1627
1628 BOOT:
1629 {
1630 #ifdef USE_ITHREADS
1631     SV *my_pool_sv = *hv_fetch(PL_modglobal, MY_POOL_KEY,
1632                                sizeof(MY_POOL_KEY)-1, TRUE);
1633     my_pool_t *my_poolp = (my_pool_t*)SvPVX(newSV(sizeof(my_pool_t)-1));
1634
1635     MY_CXT_INIT;
1636
1637     Zero(my_poolp, 1, my_pool_t);
1638     sv_setuv(my_pool_sv, PTR2UV(my_poolp));
1639
1640     PL_perl_destruct_level = 2;
1641     MUTEX_INIT(&MY_POOL.create_destruct_mutex);
1642     MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
1643
1644     PL_threadhook = &Perl_ithread_hook;
1645
1646     MY_POOL.tid_counter = 1;
1647 #  ifdef THREAD_CREATE_NEEDS_STACK
1648     MY_POOL.default_stack_size = THREAD_CREATE_NEEDS_STACK;
1649 #  endif
1650
1651     /* The 'main' thread is thread 0.
1652      * It is detached (unjoinable) and immortal.
1653      */
1654
1655     MUTEX_INIT(&MY_POOL.main_thread.mutex);
1656
1657     /* Head of the threads list */
1658     MY_POOL.main_thread.next = &MY_POOL.main_thread;
1659     MY_POOL.main_thread.prev = &MY_POOL.main_thread;
1660
1661     MY_POOL.main_thread.count = 1;                  /* Immortal */
1662
1663     MY_POOL.main_thread.interp = aTHX;
1664     MY_POOL.main_thread.state = PERL_ITHR_DETACHED; /* Detached */
1665     MY_POOL.main_thread.stack_size = MY_POOL.default_stack_size;
1666 #  ifdef WIN32
1667     MY_POOL.main_thread.thr = GetCurrentThreadId();
1668 #  else
1669     MY_POOL.main_thread.thr = pthread_self();
1670 #  endif
1671
1672     S_ithread_set(aTHX_ &MY_POOL.main_thread);
1673     MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
1674 #endif /* USE_ITHREADS */
1675 }