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