45b08d1b2dd70b4b10244dd8bbcbae0ab0e81622
[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 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 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 *returnav;
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     dSP;
86     I32 oldmark = TOPMARK;
87     I32 oldscope = scopestack_ix;
88     I32 retval;
89     AV *returnav;
90     int i, ret;
91     dJMPENV;
92
93     /* Don't call *anything* requiring dTHR until after pthread_setspecific */
94     /*
95      * Wait until our creator releases us. If we didn't do this, then
96      * it would be potentially possible for out thread to carry on and
97      * do stuff before our creator fills in our "self" field. For example,
98      * if we went and created another thread which tried to JOIN with us,
99      * then we'd be in a mess.
100      */
101     MUTEX_LOCK(&thr->mutex);
102     MUTEX_UNLOCK(&thr->mutex);
103
104     /*
105      * It's safe to wait until now to set the thread-specific pointer
106      * from our pthread_t structure to our struct thread, since we're
107      * the only thread who can get at it anyway.
108      */
109     SET_THR(thr);
110
111     /* Only now can we use SvPEEK (which calls sv_newmortal which does dTHR) */
112     DEBUG_L(PerlIO_printf(PerlIO_stderr(), "new thread %p starting at %s\n",
113                           thr, SvPEEK(TOPs)));
114
115     JMPENV_PUSH(ret);
116     switch (ret) {
117     case 3:
118         PerlIO_printf(PerlIO_stderr(), "panic: threadstart\n");
119         /* fall through */
120     case 1:
121         STATUS_ALL_FAILURE;
122         /* fall through */
123     case 2:
124         /* my_exit() was called */
125         while (scopestack_ix > oldscope)
126             LEAVE;
127         JMPENV_POP;
128         av_store(returnav, 0, newSViv(statusvalue));
129         goto finishoff;
130     }
131
132     /* Now duplicate most of perl_call_sv but with a few twists */
133     op = (OP*)&myop;
134     Zero(op, 1, LOGOP);
135     myop.op_flags = OPf_STACKED;
136     myop.op_next = Nullop;
137     myop.op_flags |= OPf_KNOW;
138     myop.op_flags |= OPf_WANT_LIST;
139     op = pp_entersub(ARGS);
140     if (op)
141         runops();
142     SPAGAIN;
143     retval = sp - (stack_base + oldmark);
144     sp = stack_base + oldmark + 1;
145     DEBUG_L(for (i = 1; i <= retval; i++)
146                 PerlIO_printf(PerlIO_stderr(),
147                               "%p returnav[%d] = %s\n",
148                               thr, i, SvPEEK(sp[i - 1]));)
149     returnav = newAV();
150     av_store(returnav, 0, newSVpv("", 0));
151     for (i = 1; i <= retval; i++, sp++)
152         sv_setsv(*av_fetch(returnav, i, TRUE), SvREFCNT_inc(*sp));
153     
154   finishoff:
155 #if 0    
156     /* removed for debug */
157     SvREFCNT_dec(curstack);
158 #endif
159     SvREFCNT_dec(cvcache);
160     Safefree(markstack);
161     Safefree(scopestack);
162     Safefree(savestack);
163     Safefree(retstack);
164     Safefree(cxstack);
165     Safefree(tmps_stack);
166
167     MUTEX_LOCK(&thr->mutex);
168     DEBUG_L(PerlIO_printf(PerlIO_stderr(),
169                           "%p: threadstart finishing: state is %u\n",
170                           thr, ThrSTATE(thr)));
171     switch (ThrSTATE(thr)) {
172     case THRf_R_JOINABLE:
173         ThrSETSTATE(thr, THRf_ZOMBIE);
174         MUTEX_UNLOCK(&thr->mutex);
175         DEBUG_L(PerlIO_printf(PerlIO_stderr(),
176                               "%p: R_JOINABLE thread finished\n", thr));
177         break;
178     case THRf_R_JOINED:
179         ThrSETSTATE(thr, THRf_DEAD);
180         MUTEX_UNLOCK(&thr->mutex);
181         remove_thread(thr);
182         DEBUG_L(PerlIO_printf(PerlIO_stderr(),
183                               "%p: R_JOINED thread finished\n", thr));
184         break;
185     case THRf_R_DETACHED:
186         ThrSETSTATE(thr, THRf_DEAD);
187         MUTEX_UNLOCK(&thr->mutex);
188         SvREFCNT_dec(returnav);
189         DEBUG_L(PerlIO_printf(PerlIO_stderr(),
190                               "%p: DETACHED thread finished\n", thr));
191         remove_thread(thr);     /* This might trigger main thread to finish */
192         break;
193     default:
194         MUTEX_UNLOCK(&thr->mutex);
195         croak("panic: illegal state %u at end of threadstart", ThrSTATE(thr));
196         /* NOTREACHED */
197     }
198     return THREAD_RET_CAST(returnav);   /* Available for anyone to join with */
199                                         /* us unless we're detached, in which */
200                                         /* case noone sees the value anyway. */
201 #endif    
202 #else
203     return THREAD_RET_CAST(NULL);
204 #endif
205 }
206
207 static SV *
208 newthread (SV *startsv, AV *initargs, char *Class)
209 {
210 #ifdef USE_THREADS
211     dTHR;
212     dSP;
213     Thread savethread;
214     int i;
215     SV *sv;
216     int err;
217 #ifndef THREAD_CREATE
218     sigset_t fullmask, oldmask;
219 #endif
220     
221     savethread = thr;
222     sv = newSVpv("", 0);
223     SvGROW(sv, sizeof(struct thread) + 1);
224     SvCUR_set(sv, sizeof(struct thread));
225     thr = (Thread) SvPVX(sv);
226     DEBUG_L(PerlIO_printf(PerlIO_stderr(), "%p: newthread(%s) = %p)\n",
227                           savethread, SvPEEK(startsv), thr));
228     oursv = sv; 
229     /* If we don't zero these foostack pointers, init_stacks won't init them */
230     markstack = 0;
231     scopestack = 0;
232     savestack = 0;
233     retstack = 0;
234     init_stacks(ARGS);
235     curcop = savethread->Tcurcop;       /* XXX As good a guess as any? */
236     SPAGAIN;
237     defstash = savethread->Tdefstash;   /* XXX maybe these should */
238     curstash = savethread->Tcurstash;   /* always be set to main? */
239     /* top_env? */
240     /* runlevel */
241     cvcache = newHV();
242     thr->flags = THRf_R_JOINABLE;
243     MUTEX_INIT(&thr->mutex);
244     thr->tid = ++threadnum;
245     /* Insert new thread into the circular linked list and bump nthreads */
246     MUTEX_LOCK(&threads_mutex);
247     thr->next = savethread->next;
248     thr->prev = savethread;
249     savethread->next = thr;
250     thr->next->prev = thr;
251     nthreads++;
252     MUTEX_UNLOCK(&threads_mutex);
253
254     DEBUG_L(PerlIO_printf(PerlIO_stderr(),
255                           "%p: newthread, tid is %u, preparing stack\n",
256                           savethread, thr->tid));
257     /* The following pushes the arg list and startsv onto the *new* stack */
258     PUSHMARK(sp);
259     /* Could easily speed up the following greatly */
260     for (i = 0; i <= AvFILL(initargs); i++)
261         XPUSHs(SvREFCNT_inc(*av_fetch(initargs, i, FALSE)));
262     XPUSHs(SvREFCNT_inc(startsv));
263     PUTBACK;
264
265 #ifdef THREAD_CREATE
266     err = THREAD_CREATE(thr, threadstart);
267 #else    
268     /* On your marks... */
269     MUTEX_LOCK(&thr->mutex);
270     /* Get set...  */
271     sigfillset(&fullmask);
272     if (sigprocmask(SIG_SETMASK, &fullmask, &oldmask) == -1)
273         croak("panic: sigprocmask");
274     err = pthread_create(&thr->self, pthread_attr_default,
275                          threadstart, (void*) thr);
276     /* Go */
277     MUTEX_UNLOCK(&thr->mutex);
278 #endif
279     if (err) {
280         /* Thread creation failed--clean up */
281         SvREFCNT_dec(cvcache);
282         remove_thread(thr);
283         MUTEX_DESTROY(&thr->mutex);
284         for (i = 0; i <= AvFILL(initargs); i++)
285             SvREFCNT_dec(*av_fetch(initargs, i, FALSE));
286         SvREFCNT_dec(startsv);
287         return NULL;
288     }
289 #ifdef THREAD_POST_CREATE
290     THREAD_POST_CREATE(thr);
291 #else
292     if (sigprocmask(SIG_SETMASK, &oldmask, 0))
293         croak("panic: sigprocmask");
294 #endif
295     sv = newSViv(thr->tid);
296     sv_magic(sv, oursv, '~', 0, 0);
297     SvMAGIC(sv)->mg_private = Thread_MAGIC_SIGNATURE;
298     return sv_bless(newRV_noinc(sv), gv_stashpv(Class, TRUE));
299 #else
300     croak("No threads in this perl");
301     return &sv_undef;
302 #endif
303 }
304
305 static Signal_t handle_thread_signal _((int sig));
306
307 static Signal_t
308 handle_thread_signal(int sig)
309 {
310     char c = (char) sig;
311     write(sig_pipe[0], &c, 1);
312 }
313
314 MODULE = Thread         PACKAGE = Thread
315
316 void
317 new(Class, startsv, ...)
318         char *          Class
319         SV *            startsv
320         AV *            av = av_make(items - 2, &ST(2));
321     PPCODE:
322         XPUSHs(sv_2mortal(newthread(startsv, av, Class)));
323
324 void
325 join(t)
326         Thread  t
327         AV *    av = NO_INIT
328         int     i = NO_INIT
329     PPCODE:
330 #ifdef USE_THREADS
331         DEBUG_L(PerlIO_printf(PerlIO_stderr(), "%p: joining %p (state %u)\n",
332                               thr, t, ThrSTATE(t)););
333         MUTEX_LOCK(&t->mutex);
334         switch (ThrSTATE(t)) {
335         case THRf_R_JOINABLE:
336         case THRf_R_JOINED:
337             ThrSETSTATE(t, THRf_R_JOINED);
338             MUTEX_UNLOCK(&t->mutex);
339             break;
340         case THRf_ZOMBIE:
341             ThrSETSTATE(t, THRf_DEAD);
342             MUTEX_UNLOCK(&t->mutex);
343             remove_thread(t);
344             break;
345         default:
346             MUTEX_UNLOCK(&t->mutex);
347             croak("can't join with thread");
348             /* NOTREACHED */
349         }
350         JOIN(t, &av);
351
352         /* Could easily speed up the following if necessary */
353         for (i = 0; i <= AvFILL(av); i++)
354             XPUSHs(sv_2mortal(*av_fetch(av, i, FALSE)));
355 #endif
356
357 void
358 detach(t)
359         Thread  t
360     CODE:
361 #ifdef USE_THREADS
362         DEBUG_L(PerlIO_printf(PerlIO_stderr(), "%p: detaching %p (state %u)\n",
363                               thr, t, ThrSTATE(t)););
364         MUTEX_LOCK(&t->mutex);
365         switch (ThrSTATE(t)) {
366         case THRf_R_JOINABLE:
367             ThrSETSTATE(t, THRf_R_DETACHED);
368             /* fall through */
369         case THRf_R_DETACHED:
370             DETACH(t);
371             MUTEX_UNLOCK(&t->mutex);
372             break;
373         case THRf_ZOMBIE:
374             ThrSETSTATE(t, THRf_DEAD);
375             DETACH(t);
376             MUTEX_UNLOCK(&t->mutex);
377             remove_thread(t);
378             break;
379         default:
380             MUTEX_UNLOCK(&t->mutex);
381             croak("can't detach thread");
382             /* NOTREACHED */
383         }
384 #endif
385
386 void
387 equal(t1, t2)
388         Thread  t1
389         Thread  t2
390     PPCODE:
391         PUSHs((t1 == t2) ? &sv_yes : &sv_no);
392
393 void
394 flags(t)
395         Thread  t
396     PPCODE:
397 #ifdef USE_THREADS
398         PUSHs(sv_2mortal(newSViv(t->flags)));
399 #endif
400
401 void
402 self(Class)
403         char *  Class
404     PREINIT:
405         SV *sv;
406     PPCODE:        
407 #ifdef USE_THREADS
408         sv = newSViv(thr->tid);
409         sv_magic(sv, oursv, '~', 0, 0);
410         SvMAGIC(sv)->mg_private = Thread_MAGIC_SIGNATURE;
411         PUSHs(sv_2mortal(sv_bless(newRV_noinc(sv), gv_stashpv(Class, TRUE))));
412 #endif
413
414 U32
415 tid(t)
416         Thread  t
417     CODE:
418 #ifdef USE_THREADS
419         MUTEX_LOCK(&t->mutex);
420         RETVAL = t->tid;
421         MUTEX_UNLOCK(&t->mutex);
422 #else 
423         RETVAL = 0;
424 #endif
425     OUTPUT:
426         RETVAL
427
428 void
429 DESTROY(t)
430         SV *    t
431     PPCODE:
432         PUSHs(&sv_yes);
433
434 void
435 yield()
436     CODE:
437 {
438 #ifdef USE_THREADS
439         YIELD;
440 #endif
441 }
442
443 void
444 cond_wait(sv)
445         SV *    sv
446         MAGIC * mg = NO_INIT
447 CODE:                       
448 #ifdef USE_THREADS
449         if (SvROK(sv))
450             sv = SvRV(sv);
451
452         mg = condpair_magic(sv);
453         DEBUG_L(PerlIO_printf(PerlIO_stderr(), "%p: cond_wait %p\n", thr, sv));
454         MUTEX_LOCK(MgMUTEXP(mg));
455         if (MgOWNER(mg) != thr) {
456             MUTEX_UNLOCK(MgMUTEXP(mg));
457             croak("cond_wait for lock that we don't own\n");
458         }
459         MgOWNER(mg) = 0;
460         COND_WAIT(MgCONDP(mg), MgMUTEXP(mg));
461         while (MgOWNER(mg))
462             COND_WAIT(MgOWNERCONDP(mg), MgMUTEXP(mg));
463         MgOWNER(mg) = thr;
464         MUTEX_UNLOCK(MgMUTEXP(mg));
465 #endif
466
467 void
468 cond_signal(sv)
469         SV *    sv
470         MAGIC * mg = NO_INIT
471 CODE:
472 #ifdef USE_THREADS
473         if (SvROK(sv))
474             sv = SvRV(sv);
475
476         mg = condpair_magic(sv);
477         DEBUG_L(PerlIO_printf(PerlIO_stderr(), "%p: cond_signal %p\n",thr,sv));
478         MUTEX_LOCK(MgMUTEXP(mg));
479         if (MgOWNER(mg) != thr) {
480             MUTEX_UNLOCK(MgMUTEXP(mg));
481             croak("cond_signal for lock that we don't own\n");
482         }
483         COND_SIGNAL(MgCONDP(mg));
484         MUTEX_UNLOCK(MgMUTEXP(mg));
485 #endif
486
487 void
488 cond_broadcast(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_L(PerlIO_printf(PerlIO_stderr(), "%p: cond_broadcast %p\n",
498                               thr, sv));
499         MUTEX_LOCK(MgMUTEXP(mg));
500         if (MgOWNER(mg) != thr) {
501             MUTEX_UNLOCK(MgMUTEXP(mg));
502             croak("cond_broadcast for lock that we don't own\n");
503         }
504         COND_BROADCAST(MgCONDP(mg));
505         MUTEX_UNLOCK(MgMUTEXP(mg));
506 #endif
507
508 void
509 list(Class)
510         char *  Class
511     PREINIT:
512         Thread  t;
513         AV *    av;
514         SV **   svp;
515         int     n = 0;
516     PPCODE:
517 #ifdef USE_THREADS
518         av = newAV();
519         /*
520          * Iterate until we have enough dynamic storage for all threads.
521          * We mustn't do any allocation while holding threads_mutex though.
522          */
523         MUTEX_LOCK(&threads_mutex);
524         do {
525             n = nthreads;
526             MUTEX_UNLOCK(&threads_mutex);
527             if (AvFILL(av) < n - 1) {
528                 int i = AvFILL(av);
529                 for (i = AvFILL(av); i < n - 1; i++) {
530                     SV *sv = newSViv(0);        /* fill in tid later */
531                     sv_magic(sv, 0, '~', 0, 0); /* fill in other magic later */
532                     av_push(av, sv_bless(newRV_noinc(sv),
533                                          gv_stashpv(Class, TRUE)));
534         
535                 }
536             }
537             MUTEX_LOCK(&threads_mutex);
538         } while (n < nthreads);
539         n = nthreads;   /* Get the final correct value */
540
541         /*
542          * At this point, there's enough room to fill in av.
543          * Note that we are holding threads_mutex so the list
544          * won't change out from under us but all the remaining
545          * processing is "fast" (no blocking, malloc etc.)
546          */
547         t = thr;
548         svp = AvARRAY(av);
549         do {
550             SV *sv = (SV*)SvRV(*svp);
551             sv_setiv(sv, t->tid);
552             SvMAGIC(sv)->mg_obj = SvREFCNT_inc(t->Toursv);
553             SvMAGIC(sv)->mg_flags |= MGf_REFCOUNTED;
554             SvMAGIC(sv)->mg_private = Thread_MAGIC_SIGNATURE;
555             t = t->next;
556             svp++;
557         } while (t != thr);
558         /*  */
559         MUTEX_UNLOCK(&threads_mutex);
560         /* Truncate any unneeded slots in av */
561         av_fill(av, n - 1);
562         /* Finally, push all the new objects onto the stack and drop av */
563         EXTEND(sp, n);
564         for (svp = AvARRAY(av); n > 0; n--, svp++)
565             PUSHs(*svp);
566         (void)sv_2mortal((SV*)av);
567 #endif
568
569
570 MODULE = Thread         PACKAGE = Thread::Signal
571
572 void
573 kill_sighandler_thread()
574     PPCODE:
575         write(sig_pipe[0], "\0", 1);
576         PUSHs(&sv_yes);
577
578 void
579 init_thread_signals()
580     PPCODE:
581         sighandlerp = handle_thread_signal;
582         if (pipe(sig_pipe) == -1)
583             XSRETURN_UNDEF;
584         PUSHs(&sv_yes);
585
586 SV *
587 await_signal()
588     PREINIT:
589         char c;
590         SSize_t ret;
591     CODE:
592         do {
593             ret = read(sig_pipe[1], &c, 1);
594         } while (ret == -1 && errno == EINTR);
595         if (ret == -1)
596             croak("panic: await_signal");
597         if (ret == 0)
598             XSRETURN_UNDEF;
599         RETVAL = c ? psig_ptr[c] : &sv_no;
600     OUTPUT:
601         RETVAL