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