8ae50d14a84992d6192f8ccb2f0bda7a57df4718
[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     /* temporarily pretend to be the child thread in case the
242      * XPUSHs() below want to grow the child's stack.  This is
243      * safe, since the other thread is not yet created, and we
244      * are the only ones who know about it */
245     SET_THR(thr);
246     SPAGAIN;
247     DEBUG_S(PerlIO_printf(PerlIO_stderr(),
248                           "%p: newthread (%p), tid is %u, preparing stack\n",
249                           savethread, thr, thr->tid));
250     /* The following pushes the arg list and startsv onto the *new* stack */
251     PUSHMARK(SP);
252     /* Could easily speed up the following greatly */
253     for (i = 0; i <= AvFILL(initargs); i++)
254         XPUSHs(SvREFCNT_inc(*av_fetch(initargs, i, FALSE)));
255     XPUSHs(SvREFCNT_inc(startsv));
256     PUTBACK;
257
258     /* On your marks... */
259     SET_THR(savethread);
260     MUTEX_LOCK(&thr->mutex);
261
262 #ifdef THREAD_CREATE
263     err = THREAD_CREATE(thr, threadstart);
264 #else    
265     /* Get set...  */
266     sigfillset(&fullmask);
267     if (sigprocmask(SIG_SETMASK, &fullmask, &oldmask) == -1)
268         croak("panic: sigprocmask");
269     err = 0;
270     if (!attr_inited) {
271         attr_inited = 1;
272         err = pthread_attr_init(&attr);
273 #  ifdef PTHREAD_ATTR_SETDETACHSTATE
274         if (err == 0)
275             err = PTHREAD_ATTR_SETDETACHSTATE(&attr, attr_joinable);
276
277 #  else
278         croak("panic: can't pthread_attr_setdetachstate");
279 #  endif
280     }
281     if (err == 0)
282         err = PTHREAD_CREATE(&thr->self, attr, threadstart, (void*) thr);
283 #endif
284
285     if (err) {
286         MUTEX_UNLOCK(&thr->mutex);
287         DEBUG_S(PerlIO_printf(PerlIO_stderr(),
288                               "%p: create of %p failed %d\n",
289                               savethread, thr, err));
290         /* Thread creation failed--clean up */
291         SvREFCNT_dec(thr->cvcache);
292         remove_thread(thr);
293         MUTEX_DESTROY(&thr->mutex);
294         for (i = 0; i <= AvFILL(initargs); i++)
295             SvREFCNT_dec(*av_fetch(initargs, i, FALSE));
296         SvREFCNT_dec(startsv);
297         return NULL;
298     }
299
300 #ifdef THREAD_POST_CREATE
301     THREAD_POST_CREATE(thr);
302 #else
303     if (sigprocmask(SIG_SETMASK, &oldmask, 0))
304         croak("panic: sigprocmask");
305 #endif
306
307     sv = newSViv(thr->tid);
308     sv_magic(sv, thr->oursv, '~', 0, 0);
309     SvMAGIC(sv)->mg_private = Thread_MAGIC_SIGNATURE;
310     sv = sv_bless(newRV_noinc(sv), gv_stashpv(classname, TRUE));
311
312     /* Go */
313     MUTEX_UNLOCK(&thr->mutex);
314
315     return sv;
316 #else
317     croak("No threads in this perl");
318     return &PL_sv_undef;
319 #endif
320 }
321
322 static Signal_t handle_thread_signal (int sig);
323
324 static Signal_t
325 handle_thread_signal(int sig)
326 {
327     unsigned char c = (unsigned char) sig;
328     /*
329      * We're not really allowed to call fprintf in a signal handler
330      * so don't be surprised if this isn't robust while debugging
331      * with -DL.
332      */
333     DEBUG_S(PerlIO_printf(PerlIO_stderr(),
334             "handle_thread_signal: got signal %d\n", sig););
335     write(sig_pipe[1], &c, 1);
336 }
337
338 MODULE = Thread         PACKAGE = Thread
339 PROTOTYPES: DISABLE
340
341 void
342 new(classname, startsv, ...)
343         char *          classname
344         SV *            startsv
345         AV *            av = av_make(items - 2, &ST(2));
346     PPCODE:
347         XPUSHs(sv_2mortal(newthread(startsv, av, classname)));
348
349 void
350 join(t)
351         Thread  t
352         AV *    av = NO_INIT
353         int     i = NO_INIT
354     PPCODE:
355 #ifdef USE_THREADS
356         DEBUG_S(PerlIO_printf(PerlIO_stderr(), "%p: joining %p (state %u)\n",
357                               thr, t, ThrSTATE(t)););
358         MUTEX_LOCK(&t->mutex);
359         switch (ThrSTATE(t)) {
360         case THRf_R_JOINABLE:
361         case THRf_R_JOINED:
362             ThrSETSTATE(t, THRf_R_JOINED);
363             MUTEX_UNLOCK(&t->mutex);
364             break;
365         case THRf_ZOMBIE:
366             ThrSETSTATE(t, THRf_DEAD);
367             MUTEX_UNLOCK(&t->mutex);
368             remove_thread(t);
369             break;
370         default:
371             MUTEX_UNLOCK(&t->mutex);
372             croak("can't join with thread");
373             /* NOTREACHED */
374         }
375         JOIN(t, &av);
376
377         if (SvTRUE(*av_fetch(av, 0, FALSE))) {
378             /* Could easily speed up the following if necessary */
379             for (i = 1; i <= AvFILL(av); i++)
380                 XPUSHs(sv_2mortal(*av_fetch(av, i, FALSE)));
381         } else {
382             STRLEN n_a;
383             char *mess = SvPV(*av_fetch(av, 1, FALSE), n_a);
384             DEBUG_S(PerlIO_printf(PerlIO_stderr(),
385                                   "%p: join propagating die message: %s\n",
386                                   thr, mess));
387             croak(mess);
388         }
389 #endif
390
391 void
392 detach(t)
393         Thread  t
394     CODE:
395 #ifdef USE_THREADS
396         DEBUG_S(PerlIO_printf(PerlIO_stderr(), "%p: detaching %p (state %u)\n",
397                               thr, t, ThrSTATE(t)););
398         MUTEX_LOCK(&t->mutex);
399         switch (ThrSTATE(t)) {
400         case THRf_R_JOINABLE:
401             ThrSETSTATE(t, THRf_R_DETACHED);
402             /* fall through */
403         case THRf_R_DETACHED:
404             DETACH(t);
405             MUTEX_UNLOCK(&t->mutex);
406             break;
407         case THRf_ZOMBIE:
408             ThrSETSTATE(t, THRf_DEAD);
409             DETACH(t);
410             MUTEX_UNLOCK(&t->mutex);
411             remove_thread(t);
412             break;
413         default:
414             MUTEX_UNLOCK(&t->mutex);
415             croak("can't detach thread");
416             /* NOTREACHED */
417         }
418 #endif
419
420 void
421 equal(t1, t2)
422         Thread  t1
423         Thread  t2
424     PPCODE:
425         PUSHs((t1 == t2) ? &PL_sv_yes : &PL_sv_no);
426
427 void
428 flags(t)
429         Thread  t
430     PPCODE:
431 #ifdef USE_THREADS
432         PUSHs(sv_2mortal(newSViv(t->flags)));
433 #endif
434
435 void
436 self(classname)
437         char *  classname
438     PREINIT:
439         SV *sv;
440     PPCODE:        
441 #ifdef USE_THREADS
442         sv = newSViv(thr->tid);
443         sv_magic(sv, thr->oursv, '~', 0, 0);
444         SvMAGIC(sv)->mg_private = Thread_MAGIC_SIGNATURE;
445         PUSHs(sv_2mortal(sv_bless(newRV_noinc(sv),
446                                   gv_stashpv(classname, TRUE))));
447 #endif
448
449 U32
450 tid(t)
451         Thread  t
452     CODE:
453 #ifdef USE_THREADS
454         MUTEX_LOCK(&t->mutex);
455         RETVAL = t->tid;
456         MUTEX_UNLOCK(&t->mutex);
457 #else 
458         RETVAL = 0;
459 #endif
460     OUTPUT:
461         RETVAL
462
463 void
464 DESTROY(t)
465         SV *    t
466     PPCODE:
467         PUSHs(&PL_sv_yes);
468
469 void
470 yield()
471     CODE:
472 {
473 #ifdef USE_THREADS
474         YIELD;
475 #endif
476 }
477
478 void
479 cond_wait(sv)
480         SV *    sv
481         MAGIC * mg = NO_INIT
482 CODE:                       
483 #ifdef USE_THREADS
484         if (SvROK(sv))
485             sv = SvRV(sv);
486
487         mg = condpair_magic(sv);
488         DEBUG_S(PerlIO_printf(PerlIO_stderr(), "%p: cond_wait %p\n", thr, sv));
489         MUTEX_LOCK(MgMUTEXP(mg));
490         if (MgOWNER(mg) != thr) {
491             MUTEX_UNLOCK(MgMUTEXP(mg));
492             croak("cond_wait for lock that we don't own\n");
493         }
494         MgOWNER(mg) = 0;
495         COND_SIGNAL(MgOWNERCONDP(mg));
496         COND_WAIT(MgCONDP(mg), MgMUTEXP(mg));
497         while (MgOWNER(mg))
498             COND_WAIT(MgOWNERCONDP(mg), MgMUTEXP(mg));
499         MgOWNER(mg) = thr;
500         MUTEX_UNLOCK(MgMUTEXP(mg));
501 #endif
502
503 void
504 cond_signal(sv)
505         SV *    sv
506         MAGIC * mg = NO_INIT
507 CODE:
508 #ifdef USE_THREADS
509         if (SvROK(sv))
510             sv = SvRV(sv);
511
512         mg = condpair_magic(sv);
513         DEBUG_S(PerlIO_printf(PerlIO_stderr(), "%p: cond_signal %p\n",thr,sv));
514         MUTEX_LOCK(MgMUTEXP(mg));
515         if (MgOWNER(mg) != thr) {
516             MUTEX_UNLOCK(MgMUTEXP(mg));
517             croak("cond_signal for lock that we don't own\n");
518         }
519         COND_SIGNAL(MgCONDP(mg));
520         MUTEX_UNLOCK(MgMUTEXP(mg));
521 #endif
522
523 void
524 cond_broadcast(sv)
525         SV *    sv
526         MAGIC * mg = NO_INIT
527 CODE: 
528 #ifdef USE_THREADS
529         if (SvROK(sv))
530             sv = SvRV(sv);
531
532         mg = condpair_magic(sv);
533         DEBUG_S(PerlIO_printf(PerlIO_stderr(), "%p: cond_broadcast %p\n",
534                               thr, sv));
535         MUTEX_LOCK(MgMUTEXP(mg));
536         if (MgOWNER(mg) != thr) {
537             MUTEX_UNLOCK(MgMUTEXP(mg));
538             croak("cond_broadcast for lock that we don't own\n");
539         }
540         COND_BROADCAST(MgCONDP(mg));
541         MUTEX_UNLOCK(MgMUTEXP(mg));
542 #endif
543
544 void
545 list(classname)
546         char *  classname
547     PREINIT:
548         Thread  t;
549         AV *    av;
550         SV **   svp;
551         int     n = 0;
552     PPCODE:
553 #ifdef USE_THREADS
554         av = newAV();
555         /*
556          * Iterate until we have enough dynamic storage for all threads.
557          * We mustn't do any allocation while holding threads_mutex though.
558          */
559         MUTEX_LOCK(&PL_threads_mutex);
560         do {
561             n = PL_nthreads;
562             MUTEX_UNLOCK(&PL_threads_mutex);
563             if (AvFILL(av) < n - 1) {
564                 int i = AvFILL(av);
565                 for (i = AvFILL(av); i < n - 1; i++) {
566                     SV *sv = newSViv(0);        /* fill in tid later */
567                     sv_magic(sv, 0, '~', 0, 0); /* fill in other magic later */
568                     av_push(av, sv_bless(newRV_noinc(sv),
569                                          gv_stashpv(classname, TRUE)));
570         
571                 }
572             }
573             MUTEX_LOCK(&PL_threads_mutex);
574         } while (n < PL_nthreads);
575         n = PL_nthreads;        /* Get the final correct value */
576
577         /*
578          * At this point, there's enough room to fill in av.
579          * Note that we are holding threads_mutex so the list
580          * won't change out from under us but all the remaining
581          * processing is "fast" (no blocking, malloc etc.)
582          */
583         t = thr;
584         svp = AvARRAY(av);
585         do {
586             SV *sv = (SV*)SvRV(*svp);
587             sv_setiv(sv, t->tid);
588             SvMAGIC(sv)->mg_obj = SvREFCNT_inc(t->oursv);
589             SvMAGIC(sv)->mg_flags |= MGf_REFCOUNTED;
590             SvMAGIC(sv)->mg_private = Thread_MAGIC_SIGNATURE;
591             t = t->next;
592             svp++;
593         } while (t != thr);
594         /*  */
595         MUTEX_UNLOCK(&PL_threads_mutex);
596         /* Truncate any unneeded slots in av */
597         av_fill(av, n - 1);
598         /* Finally, push all the new objects onto the stack and drop av */
599         EXTEND(SP, n);
600         for (svp = AvARRAY(av); n > 0; n--, svp++)
601             PUSHs(*svp);
602         (void)sv_2mortal((SV*)av);
603 #endif
604
605
606 MODULE = Thread         PACKAGE = Thread::Signal
607
608 void
609 kill_sighandler_thread()
610     PPCODE:
611         write(sig_pipe[1], "\0", 1);
612         PUSHs(&PL_sv_yes);
613
614 void
615 init_thread_signals()
616     PPCODE:
617         PL_sighandlerp = handle_thread_signal;
618         if (pipe(sig_pipe) == -1)
619             XSRETURN_UNDEF;
620         PUSHs(&PL_sv_yes);
621
622 void
623 await_signal()
624     PREINIT:
625         unsigned char c;
626         SSize_t ret;
627     CODE:
628         do {
629             ret = read(sig_pipe[0], &c, 1);
630         } while (ret == -1 && errno == EINTR);
631         if (ret == -1)
632             croak("panic: await_signal");
633         ST(0) = sv_newmortal();
634         if (ret)
635             sv_setsv(ST(0), c ? PL_psig_ptr[c] : &PL_sv_no);
636         DEBUG_S(PerlIO_printf(PerlIO_stderr(),
637                               "await_signal returning %s\n", SvPEEK(ST(0))););
638
639 MODULE = Thread         PACKAGE = Thread::Specific
640
641 void
642 data(classname = "Thread::Specific")
643         char *  classname
644     PPCODE:
645 #ifdef USE_THREADS
646         if (AvFILL(thr->specific) == -1) {
647             GV *gv = gv_fetchpv("Thread::Specific::FIELDS", TRUE, SVt_PVHV);
648             av_store(thr->specific, 0, newRV((SV*)GvHV(gv)));
649         }
650         XPUSHs(sv_bless(newRV((SV*)thr->specific),gv_stashpv(classname,TRUE)));
651 #endif