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