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