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