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