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