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