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