09751c5f1a95cbde6b41b3bd5b59e8b11e1e2b3b
[p5sagit/p5-mst-13.2.git] / ext / Thread / Thread.xs
1 #include "EXTERN.h"
2 #include "perl.h"
3 #include "XSUB.h"
4
5 /* Magic signature for Thread's mg_private is "Th" */ 
6 #define Thread_MAGIC_SIGNATURE 0x5468
7
8 #ifdef __cplusplus
9 #ifdef I_UNISTD
10 #include <unistd.h>
11 #endif
12 #endif
13 #include <fcntl.h>
14                         
15 static int sig_pipe[2];
16             
17 #ifndef THREAD_RET_TYPE
18 #define THREAD_RET_TYPE void *
19 #define THREAD_RET_CAST(x) ((THREAD_RET_TYPE) x)
20 #endif
21
22 static void
23 remove_thread(struct perl_thread *t)
24 {
25 #ifdef USE_THREADS
26     DEBUG_S(WITH_THR(PerlIO_printf(PerlIO_stderr(),
27                                    "%p: remove_thread %p\n", thr, t)));
28     MUTEX_LOCK(&PL_threads_mutex);
29     MUTEX_DESTROY(&t->mutex);
30     PL_nthreads--;
31     t->prev->next = t->next;
32     t->next->prev = t->prev;
33     COND_BROADCAST(&PL_nthreads_cond);
34     MUTEX_UNLOCK(&PL_threads_mutex);
35 #endif
36 }
37
38 static THREAD_RET_TYPE
39 threadstart(void *arg)
40 {
41 #ifdef USE_THREADS
42 #ifdef FAKE_THREADS
43     Thread savethread = thr;
44     LOGOP myop;
45     dSP;
46     I32 oldscope = PL_scopestack_ix;
47     I32 retval;
48     AV *av;
49     int i;
50
51     DEBUG_S(PerlIO_printf(PerlIO_stderr(), "new thread %p starting at %s\n",
52                           thr, SvPEEK(TOPs)));
53     thr = (Thread) arg;
54     savemark = TOPMARK;
55     thr->prev = thr->prev_run = savethread;
56     thr->next = savethread->next;
57     thr->next_run = savethread->next_run;
58     savethread->next = savethread->next_run = thr;
59     thr->wait_queue = 0;
60     thr->private = 0;
61
62     /* Now duplicate most of perl_call_sv but with a few twists */
63     PL_op = (OP*)&myop;
64     Zero(PL_op, 1, LOGOP);
65     myop.op_flags = OPf_STACKED;
66     myop.op_next = Nullop;
67     myop.op_flags |= OPf_KNOW;
68     myop.op_flags |= OPf_WANT_LIST;
69     PL_op = pp_entersub(ARGS);
70     DEBUG_S(if (!PL_op)
71             PerlIO_printf(PerlIO_stderr(), "thread starts at Nullop\n"));
72     /*
73      * When this thread is next scheduled, we start in the right
74      * place. When the thread runs off the end of the sub, perl.c
75      * handles things, using savemark to figure out how much of the
76      * stack is the return value for any join.
77      */
78     thr = savethread;           /* back to the old thread */
79     return 0;
80 #else
81     Thread thr = (Thread) arg;
82     LOGOP myop;
83     djSP;
84     I32 oldmark = TOPMARK;
85     I32 oldscope = PL_scopestack_ix;
86     I32 retval;
87     SV *sv;
88     AV *av = newAV();
89     int i, ret;
90     dJMPENV;
91     DEBUG_S(PerlIO_printf(PerlIO_stderr(), "new thread %p waiting to start\n",
92                           thr));
93
94     /* Don't call *anything* requiring dTHR until after SET_THR() */
95     /*
96      * Wait until our creator releases us. If we didn't do this, then
97      * it would be potentially possible for out thread to carry on and
98      * do stuff before our creator fills in our "self" field. For example,
99      * if we went and created another thread which tried to JOIN with us,
100      * then we'd be in a mess.
101      */
102     MUTEX_LOCK(&thr->mutex);
103     MUTEX_UNLOCK(&thr->mutex);
104
105     /*
106      * It's safe to wait until now to set the thread-specific pointer
107      * from our pthread_t structure to our struct perl_thread, since
108      * we're the only thread who can get at it anyway.
109      */
110     SET_THR(thr);
111
112     /* Only now can we use SvPEEK (which calls sv_newmortal which does dTHR) */
113     DEBUG_S(PerlIO_printf(PerlIO_stderr(), "new thread %p starting at %s\n",
114                           thr, SvPEEK(TOPs)));
115
116     sv = POPs;
117     PUTBACK;
118     ENTER;
119     SAVETMPS;
120     perl_call_sv(sv, G_ARRAY|G_EVAL);
121     SPAGAIN;
122     retval = SP - (PL_stack_base + oldmark);
123     SP = PL_stack_base + oldmark + 1;
124     if (SvCUR(thr->errsv)) {
125         MUTEX_LOCK(&thr->mutex);
126         thr->flags |= THRf_DID_DIE;
127         MUTEX_UNLOCK(&thr->mutex);
128         av_store(av, 0, &PL_sv_no);
129         av_store(av, 1, newSVsv(thr->errsv));
130         DEBUG_S(PerlIO_printf(PerlIO_stderr(), "%p died: %s\n",
131                               thr, SvPV(thr->errsv, PL_na)));
132     } else {
133         DEBUG_S(STMT_START {
134             for (i = 1; i <= retval; i++) {
135                 PerlIO_printf(PerlIO_stderr(), "%p return[%d] = %s\n",
136                                 thr, i, SvPEEK(SP[i - 1]));
137             }
138         } STMT_END);
139         av_store(av, 0, &PL_sv_yes);
140         for (i = 1; i <= retval; i++, SP++)
141             sv_setsv(*av_fetch(av, i, TRUE), SvREFCNT_inc(*SP));
142     }
143     FREETMPS;
144     LEAVE;
145
146   finishoff:
147 #if 0    
148     /* removed for debug */
149     SvREFCNT_dec(PL_curstack);
150 #endif
151     SvREFCNT_dec(thr->cvcache);
152     SvREFCNT_dec(thr->threadsv);
153     SvREFCNT_dec(thr->specific);
154     SvREFCNT_dec(thr->errsv);
155     SvREFCNT_dec(thr->errhv);
156
157     /*Safefree(cxstack);*/
158     while (PL_curstackinfo->si_next)
159         PL_curstackinfo = PL_curstackinfo->si_next;
160     while (PL_curstackinfo) {
161         PERL_SI *p = PL_curstackinfo->si_prev;
162         SvREFCNT_dec(PL_curstackinfo->si_stack);
163         Safefree(PL_curstackinfo->si_cxstack);
164         Safefree(PL_curstackinfo);
165         PL_curstackinfo = p;
166     }    
167     Safefree(PL_markstack);
168     Safefree(PL_scopestack);
169     Safefree(PL_savestack);
170     Safefree(PL_retstack);
171     Safefree(PL_tmps_stack);
172     Safefree(PL_ofs);
173
174     SvREFCNT_dec(PL_rs);
175     SvREFCNT_dec(PL_nrs);
176     SvREFCNT_dec(PL_statname);
177     Safefree(PL_screamfirst);
178     Safefree(PL_screamnext);
179     Safefree(PL_reg_start_tmp);
180     SvREFCNT_dec(PL_lastscream);
181     SvREFCNT_dec(PL_defoutgv);
182
183     MUTEX_LOCK(&thr->mutex);
184     DEBUG_S(PerlIO_printf(PerlIO_stderr(),
185                           "%p: threadstart finishing: state is %u\n",
186                           thr, ThrSTATE(thr)));
187     switch (ThrSTATE(thr)) {
188     case THRf_R_JOINABLE:
189         ThrSETSTATE(thr, THRf_ZOMBIE);
190         MUTEX_UNLOCK(&thr->mutex);
191         DEBUG_S(PerlIO_printf(PerlIO_stderr(),
192                               "%p: R_JOINABLE thread finished\n", thr));
193         break;
194     case THRf_R_JOINED:
195         ThrSETSTATE(thr, THRf_DEAD);
196         MUTEX_UNLOCK(&thr->mutex);
197         remove_thread(thr);
198         DEBUG_S(PerlIO_printf(PerlIO_stderr(),
199                               "%p: R_JOINED thread finished\n", thr));
200         break;
201     case THRf_R_DETACHED:
202         ThrSETSTATE(thr, THRf_DEAD);
203         MUTEX_UNLOCK(&thr->mutex);
204         SvREFCNT_dec(av);
205         DEBUG_S(PerlIO_printf(PerlIO_stderr(),
206                               "%p: DETACHED thread finished\n", thr));
207         remove_thread(thr);     /* This might trigger main thread to finish */
208         break;
209     default:
210         MUTEX_UNLOCK(&thr->mutex);
211         croak("panic: illegal state %u at end of threadstart", ThrSTATE(thr));
212         /* NOTREACHED */
213     }
214     return THREAD_RET_CAST(av); /* Available for anyone to join with */
215                                         /* us unless we're detached, in which */
216                                         /* case noone sees the value anyway. */
217 #endif    
218 #else
219     return THREAD_RET_CAST(NULL);
220 #endif
221 }
222
223 static SV *
224 newthread (SV *startsv, AV *initargs, char *classname)
225 {
226 #ifdef USE_THREADS
227     dSP;
228     Thread savethread;
229     int i;
230     SV *sv;
231     int err;
232 #ifndef THREAD_CREATE
233     static pthread_attr_t attr;
234     static int attr_inited = 0;
235     sigset_t fullmask, oldmask;
236     static int attr_joinable = PTHREAD_CREATE_JOINABLE;
237 #endif
238
239     savethread = thr;
240     thr = new_struct_thread(thr);
241     SPAGAIN;
242     DEBUG_S(PerlIO_printf(PerlIO_stderr(),
243                           "%p: newthread (%p), tid is %u, preparing stack\n",
244                           savethread, thr, thr->tid));
245     /* The following pushes the arg list and startsv onto the *new* stack */
246     PUSHMARK(SP);
247     /* Could easily speed up the following greatly */
248     for (i = 0; i <= AvFILL(initargs); i++)
249         XPUSHs(SvREFCNT_inc(*av_fetch(initargs, i, FALSE)));
250     XPUSHs(SvREFCNT_inc(startsv));
251     PUTBACK;
252 #ifdef THREAD_CREATE
253     err = THREAD_CREATE(thr, threadstart);
254 #else    
255     /* On your marks... */
256     MUTEX_LOCK(&thr->mutex);
257     /* Get set...  */
258     sigfillset(&fullmask);
259     if (sigprocmask(SIG_SETMASK, &fullmask, &oldmask) == -1)
260         croak("panic: sigprocmask");
261     err = 0;
262     if (!attr_inited) {
263         attr_inited = 1;
264         err = pthread_attr_init(&attr);
265 #  ifdef PTHREAD_ATTR_SETDETACHSTATE
266         if (err == 0)
267             err = PTHREAD_ATTR_SETDETACHSTATE(&attr, attr_joinable);
268
269 #  else
270         croak("panic: can't pthread_attr_setdetachstate");
271 #  endif
272     }
273     if (err == 0)
274         err = PTHREAD_CREATE(&thr->self, attr, threadstart, (void*) thr);
275     /* Go */
276     MUTEX_UNLOCK(&thr->mutex);
277 #endif
278     if (err) {
279         DEBUG_S(PerlIO_printf(PerlIO_stderr(),
280                               "%p: create of %p failed %d\n",
281                               savethread, thr, err));
282         /* Thread creation failed--clean up */
283         SvREFCNT_dec(thr->cvcache);
284         remove_thread(thr);
285         MUTEX_DESTROY(&thr->mutex);
286         for (i = 0; i <= AvFILL(initargs); i++)
287             SvREFCNT_dec(*av_fetch(initargs, i, FALSE));
288         SvREFCNT_dec(startsv);
289         return NULL;
290     }
291 #ifdef THREAD_POST_CREATE
292     THREAD_POST_CREATE(thr);
293 #else
294     if (sigprocmask(SIG_SETMASK, &oldmask, 0))
295         croak("panic: sigprocmask");
296 #endif
297     sv = newSViv(thr->tid);
298     sv_magic(sv, thr->oursv, '~', 0, 0);
299     SvMAGIC(sv)->mg_private = Thread_MAGIC_SIGNATURE;
300     return sv_bless(newRV_noinc(sv), gv_stashpv(classname, TRUE));
301 #else
302     croak("No threads in this perl");
303     return &PL_sv_undef;
304 #endif
305 }
306
307 static Signal_t handle_thread_signal _((int sig));
308
309 static Signal_t
310 handle_thread_signal(int sig)
311 {
312     unsigned char c = (unsigned char) sig;
313     /*
314      * We're not really allowed to call fprintf in a signal handler
315      * so don't be surprised if this isn't robust while debugging
316      * with -DL.
317      */
318     DEBUG_S(PerlIO_printf(PerlIO_stderr(),
319             "handle_thread_signal: got signal %d\n", sig););
320     write(sig_pipe[1], &c, 1);
321 }
322
323 MODULE = Thread         PACKAGE = Thread
324 PROTOTYPES: DISABLE
325
326 void
327 new(classname, startsv, ...)
328         char *          classname
329         SV *            startsv
330         AV *            av = av_make(items - 2, &ST(2));
331     PPCODE:
332         XPUSHs(sv_2mortal(newthread(startsv, av, classname)));
333
334 void
335 join(t)
336         Thread  t
337         AV *    av = NO_INIT
338         int     i = NO_INIT
339     PPCODE:
340 #ifdef USE_THREADS
341         DEBUG_S(PerlIO_printf(PerlIO_stderr(), "%p: joining %p (state %u)\n",
342                               thr, t, ThrSTATE(t)););
343         MUTEX_LOCK(&t->mutex);
344         switch (ThrSTATE(t)) {
345         case THRf_R_JOINABLE:
346         case THRf_R_JOINED:
347             ThrSETSTATE(t, THRf_R_JOINED);
348             MUTEX_UNLOCK(&t->mutex);
349             break;
350         case THRf_ZOMBIE:
351             ThrSETSTATE(t, THRf_DEAD);
352             MUTEX_UNLOCK(&t->mutex);
353             remove_thread(t);
354             break;
355         default:
356             MUTEX_UNLOCK(&t->mutex);
357             croak("can't join with thread");
358             /* NOTREACHED */
359         }
360         JOIN(t, &av);
361
362         if (SvTRUE(*av_fetch(av, 0, FALSE))) {
363             /* Could easily speed up the following if necessary */
364             for (i = 1; i <= AvFILL(av); i++)
365                 XPUSHs(sv_2mortal(*av_fetch(av, i, FALSE)));
366         } else {
367             char *mess = SvPV(*av_fetch(av, 1, FALSE), PL_na);
368             DEBUG_S(PerlIO_printf(PerlIO_stderr(),
369                                   "%p: join propagating die message: %s\n",
370                                   thr, mess));
371             croak(mess);
372         }
373 #endif
374
375 void
376 detach(t)
377         Thread  t
378     CODE:
379 #ifdef USE_THREADS
380         DEBUG_S(PerlIO_printf(PerlIO_stderr(), "%p: detaching %p (state %u)\n",
381                               thr, t, ThrSTATE(t)););
382         MUTEX_LOCK(&t->mutex);
383         switch (ThrSTATE(t)) {
384         case THRf_R_JOINABLE:
385             ThrSETSTATE(t, THRf_R_DETACHED);
386             /* fall through */
387         case THRf_R_DETACHED:
388             DETACH(t);
389             MUTEX_UNLOCK(&t->mutex);
390             break;
391         case THRf_ZOMBIE:
392             ThrSETSTATE(t, THRf_DEAD);
393             DETACH(t);
394             MUTEX_UNLOCK(&t->mutex);
395             remove_thread(t);
396             break;
397         default:
398             MUTEX_UNLOCK(&t->mutex);
399             croak("can't detach thread");
400             /* NOTREACHED */
401         }
402 #endif
403
404 void
405 equal(t1, t2)
406         Thread  t1
407         Thread  t2
408     PPCODE:
409         PUSHs((t1 == t2) ? &PL_sv_yes : &PL_sv_no);
410
411 void
412 flags(t)
413         Thread  t
414     PPCODE:
415 #ifdef USE_THREADS
416         PUSHs(sv_2mortal(newSViv(t->flags)));
417 #endif
418
419 void
420 self(classname)
421         char *  classname
422     PREINIT:
423         SV *sv;
424     PPCODE:        
425 #ifdef USE_THREADS
426         sv = newSViv(thr->tid);
427         sv_magic(sv, thr->oursv, '~', 0, 0);
428         SvMAGIC(sv)->mg_private = Thread_MAGIC_SIGNATURE;
429         PUSHs(sv_2mortal(sv_bless(newRV_noinc(sv),
430                                   gv_stashpv(classname, TRUE))));
431 #endif
432
433 U32
434 tid(t)
435         Thread  t
436     CODE:
437 #ifdef USE_THREADS
438         MUTEX_LOCK(&t->mutex);
439         RETVAL = t->tid;
440         MUTEX_UNLOCK(&t->mutex);
441 #else 
442         RETVAL = 0;
443 #endif
444     OUTPUT:
445         RETVAL
446
447 void
448 DESTROY(t)
449         SV *    t
450     PPCODE:
451         PUSHs(&PL_sv_yes);
452
453 void
454 yield()
455     CODE:
456 {
457 #ifdef USE_THREADS
458         YIELD;
459 #endif
460 }
461
462 void
463 cond_wait(sv)
464         SV *    sv
465         MAGIC * mg = NO_INIT
466 CODE:                       
467 #ifdef USE_THREADS
468         if (SvROK(sv))
469             sv = SvRV(sv);
470
471         mg = condpair_magic(sv);
472         DEBUG_S(PerlIO_printf(PerlIO_stderr(), "%p: cond_wait %p\n", thr, sv));
473         MUTEX_LOCK(MgMUTEXP(mg));
474         if (MgOWNER(mg) != thr) {
475             MUTEX_UNLOCK(MgMUTEXP(mg));
476             croak("cond_wait for lock that we don't own\n");
477         }
478         MgOWNER(mg) = 0;
479         COND_SIGNAL(MgOWNERCONDP(mg));
480         COND_WAIT(MgCONDP(mg), MgMUTEXP(mg));
481         while (MgOWNER(mg))
482             COND_WAIT(MgOWNERCONDP(mg), MgMUTEXP(mg));
483         MgOWNER(mg) = thr;
484         MUTEX_UNLOCK(MgMUTEXP(mg));
485 #endif
486
487 void
488 cond_signal(sv)
489         SV *    sv
490         MAGIC * mg = NO_INIT
491 CODE:
492 #ifdef USE_THREADS
493         if (SvROK(sv))
494             sv = SvRV(sv);
495
496         mg = condpair_magic(sv);
497         DEBUG_S(PerlIO_printf(PerlIO_stderr(), "%p: cond_signal %p\n",thr,sv));
498         MUTEX_LOCK(MgMUTEXP(mg));
499         if (MgOWNER(mg) != thr) {
500             MUTEX_UNLOCK(MgMUTEXP(mg));
501             croak("cond_signal for lock that we don't own\n");
502         }
503         COND_SIGNAL(MgCONDP(mg));
504         MUTEX_UNLOCK(MgMUTEXP(mg));
505 #endif
506
507 void
508 cond_broadcast(sv)
509         SV *    sv
510         MAGIC * mg = NO_INIT
511 CODE: 
512 #ifdef USE_THREADS
513         if (SvROK(sv))
514             sv = SvRV(sv);
515
516         mg = condpair_magic(sv);
517         DEBUG_S(PerlIO_printf(PerlIO_stderr(), "%p: cond_broadcast %p\n",
518                               thr, sv));
519         MUTEX_LOCK(MgMUTEXP(mg));
520         if (MgOWNER(mg) != thr) {
521             MUTEX_UNLOCK(MgMUTEXP(mg));
522             croak("cond_broadcast for lock that we don't own\n");
523         }
524         COND_BROADCAST(MgCONDP(mg));
525         MUTEX_UNLOCK(MgMUTEXP(mg));
526 #endif
527
528 void
529 list(classname)
530         char *  classname
531     PREINIT:
532         Thread  t;
533         AV *    av;
534         SV **   svp;
535         int     n = 0;
536     PPCODE:
537 #ifdef USE_THREADS
538         av = newAV();
539         /*
540          * Iterate until we have enough dynamic storage for all threads.
541          * We mustn't do any allocation while holding threads_mutex though.
542          */
543         MUTEX_LOCK(&PL_threads_mutex);
544         do {
545             n = PL_nthreads;
546             MUTEX_UNLOCK(&PL_threads_mutex);
547             if (AvFILL(av) < n - 1) {
548                 int i = AvFILL(av);
549                 for (i = AvFILL(av); i < n - 1; i++) {
550                     SV *sv = newSViv(0);        /* fill in tid later */
551                     sv_magic(sv, 0, '~', 0, 0); /* fill in other magic later */
552                     av_push(av, sv_bless(newRV_noinc(sv),
553                                          gv_stashpv(classname, TRUE)));
554         
555                 }
556             }
557             MUTEX_LOCK(&PL_threads_mutex);
558         } while (n < PL_nthreads);
559         n = PL_nthreads;        /* Get the final correct value */
560
561         /*
562          * At this point, there's enough room to fill in av.
563          * Note that we are holding threads_mutex so the list
564          * won't change out from under us but all the remaining
565          * processing is "fast" (no blocking, malloc etc.)
566          */
567         t = thr;
568         svp = AvARRAY(av);
569         do {
570             SV *sv = (SV*)SvRV(*svp);
571             sv_setiv(sv, t->tid);
572             SvMAGIC(sv)->mg_obj = SvREFCNT_inc(t->oursv);
573             SvMAGIC(sv)->mg_flags |= MGf_REFCOUNTED;
574             SvMAGIC(sv)->mg_private = Thread_MAGIC_SIGNATURE;
575             t = t->next;
576             svp++;
577         } while (t != thr);
578         /*  */
579         MUTEX_UNLOCK(&PL_threads_mutex);
580         /* Truncate any unneeded slots in av */
581         av_fill(av, n - 1);
582         /* Finally, push all the new objects onto the stack and drop av */
583         EXTEND(SP, n);
584         for (svp = AvARRAY(av); n > 0; n--, svp++)
585             PUSHs(*svp);
586         (void)sv_2mortal((SV*)av);
587 #endif
588
589
590 MODULE = Thread         PACKAGE = Thread::Signal
591
592 void
593 kill_sighandler_thread()
594     PPCODE:
595         write(sig_pipe[1], "\0", 1);
596         PUSHs(&PL_sv_yes);
597
598 void
599 init_thread_signals()
600     PPCODE:
601         PL_sighandlerp = handle_thread_signal;
602         if (pipe(sig_pipe) == -1)
603             XSRETURN_UNDEF;
604         PUSHs(&PL_sv_yes);
605
606 void
607 await_signal()
608     PREINIT:
609         unsigned char c;
610         SSize_t ret;
611     CODE:
612         do {
613             ret = read(sig_pipe[0], &c, 1);
614         } while (ret == -1 && errno == EINTR);
615         if (ret == -1)
616             croak("panic: await_signal");
617         ST(0) = sv_newmortal();
618         if (ret)
619             sv_setsv(ST(0), c ? PL_psig_ptr[c] : &PL_sv_no);
620         DEBUG_S(PerlIO_printf(PerlIO_stderr(),
621                               "await_signal returning %s\n", SvPEEK(ST(0))););
622
623 MODULE = Thread         PACKAGE = Thread::Specific
624
625 void
626 data(classname = "Thread::Specific")
627         char *  classname
628     PPCODE:
629 #ifdef USE_THREADS
630         if (AvFILL(thr->specific) == -1) {
631             GV *gv = gv_fetchpv("Thread::Specific::FIELDS", TRUE, SVt_PVHV);
632             av_store(thr->specific, 0, newRV((SV*)GvHV(gv)));
633         }
634         XPUSHs(sv_bless(newRV((SV*)thr->specific),gv_stashpv(classname,TRUE)));
635 #endif