OLD_PTHREADS_API reorganizing.
[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     perl_call_sv(sv, G_ARRAY|G_EVAL);
119     SPAGAIN;
120     retval = SP - (PL_stack_base + oldmark);
121     SP = PL_stack_base + oldmark + 1;
122     if (SvCUR(thr->errsv)) {
123         MUTEX_LOCK(&thr->mutex);
124         thr->flags |= THRf_DID_DIE;
125         MUTEX_UNLOCK(&thr->mutex);
126         av_store(av, 0, &PL_sv_no);
127         av_store(av, 1, newSVsv(thr->errsv));
128         DEBUG_S(PerlIO_printf(PerlIO_stderr(), "%p died: %s\n",
129                               thr, SvPV(thr->errsv, PL_na)));
130     } else {
131         DEBUG_S(STMT_START {
132             for (i = 1; i <= retval; i++) {
133                 PerlIO_printf(PerlIO_stderr(), "%p return[%d] = %s\n",
134                                 thr, i, SvPEEK(SP[i - 1]));
135             }
136         } STMT_END);
137         av_store(av, 0, &PL_sv_yes);
138         for (i = 1; i <= retval; i++, SP++)
139             sv_setsv(*av_fetch(av, i, TRUE), SvREFCNT_inc(*SP));
140     }
141
142   finishoff:
143 #if 0    
144     /* removed for debug */
145     SvREFCNT_dec(PL_curstack);
146 #endif
147     SvREFCNT_dec(thr->cvcache);
148     SvREFCNT_dec(thr->threadsv);
149     SvREFCNT_dec(thr->specific);
150     SvREFCNT_dec(thr->errsv);
151     SvREFCNT_dec(thr->errhv);
152
153     /*Safefree(cxstack);*/
154     while (PL_curstackinfo->si_next)
155         PL_curstackinfo = PL_curstackinfo->si_next;
156     while (PL_curstackinfo) {
157         PERL_SI *p = PL_curstackinfo->si_prev;
158         SvREFCNT_dec(PL_curstackinfo->si_stack);
159         Safefree(PL_curstackinfo->si_cxstack);
160         Safefree(PL_curstackinfo);
161         PL_curstackinfo = p;
162     }    
163     Safefree(PL_markstack);
164     Safefree(PL_scopestack);
165     Safefree(PL_savestack);
166     Safefree(PL_retstack);
167     Safefree(PL_tmps_stack);
168     Safefree(PL_ofs);
169
170     SvREFCNT_dec(PL_rs);
171     SvREFCNT_dec(PL_nrs);
172     SvREFCNT_dec(PL_statname);
173     Safefree(PL_screamfirst);
174     Safefree(PL_screamnext);
175     Safefree(PL_reg_start_tmp);
176     SvREFCNT_dec(PL_lastscream);
177     /*SvREFCNT_dec(PL_defoutgv);*/
178
179     MUTEX_LOCK(&thr->mutex);
180     DEBUG_S(PerlIO_printf(PerlIO_stderr(),
181                           "%p: threadstart finishing: state is %u\n",
182                           thr, ThrSTATE(thr)));
183     switch (ThrSTATE(thr)) {
184     case THRf_R_JOINABLE:
185         ThrSETSTATE(thr, THRf_ZOMBIE);
186         MUTEX_UNLOCK(&thr->mutex);
187         DEBUG_S(PerlIO_printf(PerlIO_stderr(),
188                               "%p: R_JOINABLE thread finished\n", thr));
189         break;
190     case THRf_R_JOINED:
191         ThrSETSTATE(thr, THRf_DEAD);
192         MUTEX_UNLOCK(&thr->mutex);
193         remove_thread(thr);
194         DEBUG_S(PerlIO_printf(PerlIO_stderr(),
195                               "%p: R_JOINED thread finished\n", thr));
196         break;
197     case THRf_R_DETACHED:
198         ThrSETSTATE(thr, THRf_DEAD);
199         MUTEX_UNLOCK(&thr->mutex);
200         SvREFCNT_dec(av);
201         DEBUG_S(PerlIO_printf(PerlIO_stderr(),
202                               "%p: DETACHED thread finished\n", thr));
203         remove_thread(thr);     /* This might trigger main thread to finish */
204         break;
205     default:
206         MUTEX_UNLOCK(&thr->mutex);
207         croak("panic: illegal state %u at end of threadstart", ThrSTATE(thr));
208         /* NOTREACHED */
209     }
210     return THREAD_RET_CAST(av); /* Available for anyone to join with */
211                                         /* us unless we're detached, in which */
212                                         /* case noone sees the value anyway. */
213 #endif    
214 #else
215     return THREAD_RET_CAST(NULL);
216 #endif
217 }
218
219 static SV *
220 newthread (SV *startsv, AV *initargs, char *classname)
221 {
222 #ifdef USE_THREADS
223     dSP;
224     Thread savethread;
225     int i;
226     SV *sv;
227     int err;
228 #ifndef THREAD_CREATE
229     static pthread_attr_t attr;
230     static int attr_inited = 0;
231     sigset_t fullmask, oldmask;
232 #endif
233     static int attr_joinable = ATTR_JOINABLE;
234
235     savethread = thr;
236     thr = new_struct_thread(thr);
237     SPAGAIN;
238     DEBUG_S(PerlIO_printf(PerlIO_stderr(),
239                           "%p: newthread (%p), tid is %u, preparing stack\n",
240                           savethread, thr, thr->tid));
241     /* The following pushes the arg list and startsv onto the *new* stack */
242     PUSHMARK(SP);
243     /* Could easily speed up the following greatly */
244     for (i = 0; i <= AvFILL(initargs); i++)
245         XPUSHs(SvREFCNT_inc(*av_fetch(initargs, i, FALSE)));
246     XPUSHs(SvREFCNT_inc(startsv));
247     PUTBACK;
248 #ifdef THREAD_CREATE
249     err = THREAD_CREATE(thr, threadstart);
250 #else    
251     /* On your marks... */
252     MUTEX_LOCK(&thr->mutex);
253     /* Get set...  */
254     sigfillset(&fullmask);
255     if (sigprocmask(SIG_SETMASK, &fullmask, &oldmask) == -1)
256         croak("panic: sigprocmask");
257     err = 0;
258     if (!attr_inited) {
259         attr_inited = 1;
260         err = pthread_attr_init(&attr);
261 #  ifdef PTHREAD_ATTR_SETDETACHSTATE
262         if (err == 0)
263             err = PTHREAD_ATTR_SETDETACHSTATE(&attr, attr_joinable);
264
265 #  else
266         croak("panic: can't pthread_attr_setdetachstate");
267 #  endif
268     }
269     if (err == 0)
270         err = PTHREAD_CREATE(&thr->self, attr, threadstart, (void*) thr);
271     /* Go */
272     MUTEX_UNLOCK(&thr->mutex);
273 #endif
274     if (err) {
275         DEBUG_S(PerlIO_printf(PerlIO_stderr(),
276                               "%p: create of %p failed %d\n",
277                               savethread, thr, err));
278         /* Thread creation failed--clean up */
279         SvREFCNT_dec(thr->cvcache);
280         remove_thread(thr);
281         MUTEX_DESTROY(&thr->mutex);
282         for (i = 0; i <= AvFILL(initargs); i++)
283             SvREFCNT_dec(*av_fetch(initargs, i, FALSE));
284         SvREFCNT_dec(startsv);
285         return NULL;
286     }
287 #ifdef THREAD_POST_CREATE
288     THREAD_POST_CREATE(thr);
289 #else
290     if (sigprocmask(SIG_SETMASK, &oldmask, 0))
291         croak("panic: sigprocmask");
292 #endif
293     sv = newSViv(thr->tid);
294     sv_magic(sv, thr->oursv, '~', 0, 0);
295     SvMAGIC(sv)->mg_private = Thread_MAGIC_SIGNATURE;
296     return sv_bless(newRV_noinc(sv), gv_stashpv(classname, TRUE));
297 #else
298     croak("No threads in this perl");
299     return &PL_sv_undef;
300 #endif
301 }
302
303 static Signal_t handle_thread_signal _((int sig));
304
305 static Signal_t
306 handle_thread_signal(int sig)
307 {
308     unsigned char c = (unsigned char) sig;
309     /*
310      * We're not really allowed to call fprintf in a signal handler
311      * so don't be surprised if this isn't robust while debugging
312      * with -DL.
313      */
314     DEBUG_S(PerlIO_printf(PerlIO_stderr(),
315             "handle_thread_signal: got signal %d\n", sig););
316     write(sig_pipe[1], &c, 1);
317 }
318
319 MODULE = Thread         PACKAGE = Thread
320 PROTOTYPES: DISABLE
321
322 void
323 new(classname, startsv, ...)
324         char *          classname
325         SV *            startsv
326         AV *            av = av_make(items - 2, &ST(2));
327     PPCODE:
328         XPUSHs(sv_2mortal(newthread(startsv, av, classname)));
329
330 void
331 join(t)
332         Thread  t
333         AV *    av = NO_INIT
334         int     i = NO_INIT
335     PPCODE:
336 #ifdef USE_THREADS
337         DEBUG_S(PerlIO_printf(PerlIO_stderr(), "%p: joining %p (state %u)\n",
338                               thr, t, ThrSTATE(t)););
339         MUTEX_LOCK(&t->mutex);
340         switch (ThrSTATE(t)) {
341         case THRf_R_JOINABLE:
342         case THRf_R_JOINED:
343             ThrSETSTATE(t, THRf_R_JOINED);
344             MUTEX_UNLOCK(&t->mutex);
345             break;
346         case THRf_ZOMBIE:
347             ThrSETSTATE(t, THRf_DEAD);
348             MUTEX_UNLOCK(&t->mutex);
349             remove_thread(t);
350             break;
351         default:
352             MUTEX_UNLOCK(&t->mutex);
353             croak("can't join with thread");
354             /* NOTREACHED */
355         }
356         JOIN(t, &av);
357
358         if (SvTRUE(*av_fetch(av, 0, FALSE))) {
359             /* Could easily speed up the following if necessary */
360             for (i = 1; i <= AvFILL(av); i++)
361                 XPUSHs(sv_2mortal(*av_fetch(av, i, FALSE)));
362         } else {
363             char *mess = SvPV(*av_fetch(av, 1, FALSE), PL_na);
364             DEBUG_S(PerlIO_printf(PerlIO_stderr(),
365                                   "%p: join propagating die message: %s\n",
366                                   thr, mess));
367             croak(mess);
368         }
369 #endif
370
371 void
372 detach(t)
373         Thread  t
374     CODE:
375 #ifdef USE_THREADS
376         DEBUG_S(PerlIO_printf(PerlIO_stderr(), "%p: detaching %p (state %u)\n",
377                               thr, t, ThrSTATE(t)););
378         MUTEX_LOCK(&t->mutex);
379         switch (ThrSTATE(t)) {
380         case THRf_R_JOINABLE:
381             ThrSETSTATE(t, THRf_R_DETACHED);
382             /* fall through */
383         case THRf_R_DETACHED:
384             DETACH(t);
385             MUTEX_UNLOCK(&t->mutex);
386             break;
387         case THRf_ZOMBIE:
388             ThrSETSTATE(t, THRf_DEAD);
389             DETACH(t);
390             MUTEX_UNLOCK(&t->mutex);
391             remove_thread(t);
392             break;
393         default:
394             MUTEX_UNLOCK(&t->mutex);
395             croak("can't detach thread");
396             /* NOTREACHED */
397         }
398 #endif
399
400 void
401 equal(t1, t2)
402         Thread  t1
403         Thread  t2
404     PPCODE:
405         PUSHs((t1 == t2) ? &PL_sv_yes : &PL_sv_no);
406
407 void
408 flags(t)
409         Thread  t
410     PPCODE:
411 #ifdef USE_THREADS
412         PUSHs(sv_2mortal(newSViv(t->flags)));
413 #endif
414
415 void
416 self(classname)
417         char *  classname
418     PREINIT:
419         SV *sv;
420     PPCODE:        
421 #ifdef USE_THREADS
422         sv = newSViv(thr->tid);
423         sv_magic(sv, thr->oursv, '~', 0, 0);
424         SvMAGIC(sv)->mg_private = Thread_MAGIC_SIGNATURE;
425         PUSHs(sv_2mortal(sv_bless(newRV_noinc(sv),
426                                   gv_stashpv(classname, TRUE))));
427 #endif
428
429 U32
430 tid(t)
431         Thread  t
432     CODE:
433 #ifdef USE_THREADS
434         MUTEX_LOCK(&t->mutex);
435         RETVAL = t->tid;
436         MUTEX_UNLOCK(&t->mutex);
437 #else 
438         RETVAL = 0;
439 #endif
440     OUTPUT:
441         RETVAL
442
443 void
444 DESTROY(t)
445         SV *    t
446     PPCODE:
447         PUSHs(&PL_sv_yes);
448
449 void
450 yield()
451     CODE:
452 {
453 #ifdef USE_THREADS
454         YIELD;
455 #endif
456 }
457
458 void
459 cond_wait(sv)
460         SV *    sv
461         MAGIC * mg = NO_INIT
462 CODE:                       
463 #ifdef USE_THREADS
464         if (SvROK(sv))
465             sv = SvRV(sv);
466
467         mg = condpair_magic(sv);
468         DEBUG_S(PerlIO_printf(PerlIO_stderr(), "%p: cond_wait %p\n", thr, sv));
469         MUTEX_LOCK(MgMUTEXP(mg));
470         if (MgOWNER(mg) != thr) {
471             MUTEX_UNLOCK(MgMUTEXP(mg));
472             croak("cond_wait for lock that we don't own\n");
473         }
474         MgOWNER(mg) = 0;
475         COND_SIGNAL(MgOWNERCONDP(mg));
476         COND_WAIT(MgCONDP(mg), MgMUTEXP(mg));
477         while (MgOWNER(mg))
478             COND_WAIT(MgOWNERCONDP(mg), MgMUTEXP(mg));
479         MgOWNER(mg) = thr;
480         MUTEX_UNLOCK(MgMUTEXP(mg));
481 #endif
482
483 void
484 cond_signal(sv)
485         SV *    sv
486         MAGIC * mg = NO_INIT
487 CODE:
488 #ifdef USE_THREADS
489         if (SvROK(sv))
490             sv = SvRV(sv);
491
492         mg = condpair_magic(sv);
493         DEBUG_S(PerlIO_printf(PerlIO_stderr(), "%p: cond_signal %p\n",thr,sv));
494         MUTEX_LOCK(MgMUTEXP(mg));
495         if (MgOWNER(mg) != thr) {
496             MUTEX_UNLOCK(MgMUTEXP(mg));
497             croak("cond_signal for lock that we don't own\n");
498         }
499         COND_SIGNAL(MgCONDP(mg));
500         MUTEX_UNLOCK(MgMUTEXP(mg));
501 #endif
502
503 void
504 cond_broadcast(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_broadcast %p\n",
514                               thr, sv));
515         MUTEX_LOCK(MgMUTEXP(mg));
516         if (MgOWNER(mg) != thr) {
517             MUTEX_UNLOCK(MgMUTEXP(mg));
518             croak("cond_broadcast for lock that we don't own\n");
519         }
520         COND_BROADCAST(MgCONDP(mg));
521         MUTEX_UNLOCK(MgMUTEXP(mg));
522 #endif
523
524 void
525 list(classname)
526         char *  classname
527     PREINIT:
528         Thread  t;
529         AV *    av;
530         SV **   svp;
531         int     n = 0;
532     PPCODE:
533 #ifdef USE_THREADS
534         av = newAV();
535         /*
536          * Iterate until we have enough dynamic storage for all threads.
537          * We mustn't do any allocation while holding threads_mutex though.
538          */
539         MUTEX_LOCK(&PL_threads_mutex);
540         do {
541             n = PL_nthreads;
542             MUTEX_UNLOCK(&PL_threads_mutex);
543             if (AvFILL(av) < n - 1) {
544                 int i = AvFILL(av);
545                 for (i = AvFILL(av); i < n - 1; i++) {
546                     SV *sv = newSViv(0);        /* fill in tid later */
547                     sv_magic(sv, 0, '~', 0, 0); /* fill in other magic later */
548                     av_push(av, sv_bless(newRV_noinc(sv),
549                                          gv_stashpv(classname, TRUE)));
550         
551                 }
552             }
553             MUTEX_LOCK(&PL_threads_mutex);
554         } while (n < PL_nthreads);
555         n = PL_nthreads;        /* Get the final correct value */
556
557         /*
558          * At this point, there's enough room to fill in av.
559          * Note that we are holding threads_mutex so the list
560          * won't change out from under us but all the remaining
561          * processing is "fast" (no blocking, malloc etc.)
562          */
563         t = thr;
564         svp = AvARRAY(av);
565         do {
566             SV *sv = (SV*)SvRV(*svp);
567             sv_setiv(sv, t->tid);
568             SvMAGIC(sv)->mg_obj = SvREFCNT_inc(t->oursv);
569             SvMAGIC(sv)->mg_flags |= MGf_REFCOUNTED;
570             SvMAGIC(sv)->mg_private = Thread_MAGIC_SIGNATURE;
571             t = t->next;
572             svp++;
573         } while (t != thr);
574         /*  */
575         MUTEX_UNLOCK(&PL_threads_mutex);
576         /* Truncate any unneeded slots in av */
577         av_fill(av, n - 1);
578         /* Finally, push all the new objects onto the stack and drop av */
579         EXTEND(SP, n);
580         for (svp = AvARRAY(av); n > 0; n--, svp++)
581             PUSHs(*svp);
582         (void)sv_2mortal((SV*)av);
583 #endif
584
585
586 MODULE = Thread         PACKAGE = Thread::Signal
587
588 void
589 kill_sighandler_thread()
590     PPCODE:
591         write(sig_pipe[1], "\0", 1);
592         PUSHs(&PL_sv_yes);
593
594 void
595 init_thread_signals()
596     PPCODE:
597         PL_sighandlerp = handle_thread_signal;
598         if (pipe(sig_pipe) == -1)
599             XSRETURN_UNDEF;
600         PUSHs(&PL_sv_yes);
601
602 void
603 await_signal()
604     PREINIT:
605         unsigned char c;
606         SSize_t ret;
607     CODE:
608         do {
609             ret = read(sig_pipe[0], &c, 1);
610         } while (ret == -1 && errno == EINTR);
611         if (ret == -1)
612             croak("panic: await_signal");
613         ST(0) = sv_newmortal();
614         if (ret)
615             sv_setsv(ST(0), c ? psig_ptr[c] : &PL_sv_no);
616         DEBUG_S(PerlIO_printf(PerlIO_stderr(),
617                               "await_signal returning %s\n", SvPEEK(ST(0))););
618
619 MODULE = Thread         PACKAGE = Thread::Specific
620
621 void
622 data(classname = "Thread::Specific")
623         char *  classname
624     PPCODE:
625 #ifdef USE_THREADS
626         if (AvFILL(thr->specific) == -1) {
627             GV *gv = gv_fetchpv("Thread::Specific::FIELDS", TRUE, SVt_PVHV);
628             av_store(thr->specific, 0, newRV((SV*)GvHV(gv)));
629         }
630         XPUSHs(sv_bless(newRV((SV*)thr->specific),gv_stashpv(classname,TRUE)));
631 #endif