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