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