e6714aae962f1c4f35c24b0d62ad77b5562eaa5b
[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     thr = new_struct_thread(thr);
223     init_stacks(ARGS);
224     SPAGAIN;
225     DEBUG_L(PerlIO_printf(PerlIO_stderr(),
226                           "%p: newthread, tid is %u, preparing stack\n",
227                           savethread, thr->tid));
228     /* The following pushes the arg list and startsv onto the *new* stack */
229     PUSHMARK(sp);
230     /* Could easily speed up the following greatly */
231     for (i = 0; i <= AvFILL(initargs); i++)
232         XPUSHs(SvREFCNT_inc(*av_fetch(initargs, i, FALSE)));
233     XPUSHs(SvREFCNT_inc(startsv));
234     PUTBACK;
235
236 #ifdef THREAD_CREATE
237     err = THREAD_CREATE(thr, threadstart);
238 #else    
239     /* On your marks... */
240     MUTEX_LOCK(&thr->mutex);
241     /* Get set...  */
242     sigfillset(&fullmask);
243     if (sigprocmask(SIG_SETMASK, &fullmask, &oldmask) == -1)
244         croak("panic: sigprocmask");
245     err = pthread_create(&thr->self, pthread_attr_default,
246                          threadstart, (void*) thr);
247     /* Go */
248     MUTEX_UNLOCK(&thr->mutex);
249 #endif
250     if (err) {
251         /* Thread creation failed--clean up */
252         SvREFCNT_dec(cvcache);
253         remove_thread(thr);
254         MUTEX_DESTROY(&thr->mutex);
255         for (i = 0; i <= AvFILL(initargs); i++)
256             SvREFCNT_dec(*av_fetch(initargs, i, FALSE));
257         SvREFCNT_dec(startsv);
258         return NULL;
259     }
260 #ifdef THREAD_POST_CREATE
261     THREAD_POST_CREATE(thr);
262 #else
263     if (sigprocmask(SIG_SETMASK, &oldmask, 0))
264         croak("panic: sigprocmask");
265 #endif
266     sv = newSViv(thr->tid);
267     sv_magic(sv, oursv, '~', 0, 0);
268     SvMAGIC(sv)->mg_private = Thread_MAGIC_SIGNATURE;
269     return sv_bless(newRV_noinc(sv), gv_stashpv(Class, TRUE));
270 #else
271     croak("No threads in this perl");
272     return &sv_undef;
273 #endif
274 }
275
276 static Signal_t handle_thread_signal _((int sig));
277
278 static Signal_t
279 handle_thread_signal(int sig)
280 {
281     char c = (char) sig;
282     write(sig_pipe[0], &c, 1);
283 }
284
285 MODULE = Thread         PACKAGE = Thread
286
287 void
288 new(Class, startsv, ...)
289         char *          Class
290         SV *            startsv
291         AV *            av = av_make(items - 2, &ST(2));
292     PPCODE:
293         XPUSHs(sv_2mortal(newthread(startsv, av, Class)));
294
295 void
296 join(t)
297         Thread  t
298         AV *    av = NO_INIT
299         int     i = NO_INIT
300     PPCODE:
301 #ifdef USE_THREADS
302         DEBUG_L(PerlIO_printf(PerlIO_stderr(), "%p: joining %p (state %u)\n",
303                               thr, t, ThrSTATE(t)););
304         MUTEX_LOCK(&t->mutex);
305         switch (ThrSTATE(t)) {
306         case THRf_R_JOINABLE:
307         case THRf_R_JOINED:
308             ThrSETSTATE(t, THRf_R_JOINED);
309             MUTEX_UNLOCK(&t->mutex);
310             break;
311         case THRf_ZOMBIE:
312             ThrSETSTATE(t, THRf_DEAD);
313             MUTEX_UNLOCK(&t->mutex);
314             remove_thread(t);
315             break;
316         default:
317             MUTEX_UNLOCK(&t->mutex);
318             croak("can't join with thread");
319             /* NOTREACHED */
320         }
321         JOIN(t, &av);
322
323         /* Could easily speed up the following if necessary */
324         for (i = 0; i <= AvFILL(av); i++)
325             XPUSHs(sv_2mortal(*av_fetch(av, i, FALSE)));
326 #endif
327
328 void
329 detach(t)
330         Thread  t
331     CODE:
332 #ifdef USE_THREADS
333         DEBUG_L(PerlIO_printf(PerlIO_stderr(), "%p: detaching %p (state %u)\n",
334                               thr, t, ThrSTATE(t)););
335         MUTEX_LOCK(&t->mutex);
336         switch (ThrSTATE(t)) {
337         case THRf_R_JOINABLE:
338             ThrSETSTATE(t, THRf_R_DETACHED);
339             /* fall through */
340         case THRf_R_DETACHED:
341             DETACH(t);
342             MUTEX_UNLOCK(&t->mutex);
343             break;
344         case THRf_ZOMBIE:
345             ThrSETSTATE(t, THRf_DEAD);
346             DETACH(t);
347             MUTEX_UNLOCK(&t->mutex);
348             remove_thread(t);
349             break;
350         default:
351             MUTEX_UNLOCK(&t->mutex);
352             croak("can't detach thread");
353             /* NOTREACHED */
354         }
355 #endif
356
357 void
358 equal(t1, t2)
359         Thread  t1
360         Thread  t2
361     PPCODE:
362         PUSHs((t1 == t2) ? &sv_yes : &sv_no);
363
364 void
365 flags(t)
366         Thread  t
367     PPCODE:
368 #ifdef USE_THREADS
369         PUSHs(sv_2mortal(newSViv(t->flags)));
370 #endif
371
372 void
373 self(Class)
374         char *  Class
375     PREINIT:
376         SV *sv;
377     PPCODE:        
378 #ifdef USE_THREADS
379         sv = newSViv(thr->tid);
380         sv_magic(sv, oursv, '~', 0, 0);
381         SvMAGIC(sv)->mg_private = Thread_MAGIC_SIGNATURE;
382         PUSHs(sv_2mortal(sv_bless(newRV_noinc(sv), gv_stashpv(Class, TRUE))));
383 #endif
384
385 U32
386 tid(t)
387         Thread  t
388     CODE:
389 #ifdef USE_THREADS
390         MUTEX_LOCK(&t->mutex);
391         RETVAL = t->tid;
392         MUTEX_UNLOCK(&t->mutex);
393 #else 
394         RETVAL = 0;
395 #endif
396     OUTPUT:
397         RETVAL
398
399 void
400 DESTROY(t)
401         SV *    t
402     PPCODE:
403         PUSHs(&sv_yes);
404
405 void
406 yield()
407     CODE:
408 {
409 #ifdef USE_THREADS
410         YIELD;
411 #endif
412 }
413
414 void
415 cond_wait(sv)
416         SV *    sv
417         MAGIC * mg = NO_INIT
418 CODE:                       
419 #ifdef USE_THREADS
420         if (SvROK(sv))
421             sv = SvRV(sv);
422
423         mg = condpair_magic(sv);
424         DEBUG_L(PerlIO_printf(PerlIO_stderr(), "%p: cond_wait %p\n", thr, sv));
425         MUTEX_LOCK(MgMUTEXP(mg));
426         if (MgOWNER(mg) != thr) {
427             MUTEX_UNLOCK(MgMUTEXP(mg));
428             croak("cond_wait for lock that we don't own\n");
429         }
430         MgOWNER(mg) = 0;
431         COND_WAIT(MgCONDP(mg), MgMUTEXP(mg));
432         while (MgOWNER(mg))
433             COND_WAIT(MgOWNERCONDP(mg), MgMUTEXP(mg));
434         MgOWNER(mg) = thr;
435         MUTEX_UNLOCK(MgMUTEXP(mg));
436 #endif
437
438 void
439 cond_signal(sv)
440         SV *    sv
441         MAGIC * mg = NO_INIT
442 CODE:
443 #ifdef USE_THREADS
444         if (SvROK(sv))
445             sv = SvRV(sv);
446
447         mg = condpair_magic(sv);
448         DEBUG_L(PerlIO_printf(PerlIO_stderr(), "%p: cond_signal %p\n",thr,sv));
449         MUTEX_LOCK(MgMUTEXP(mg));
450         if (MgOWNER(mg) != thr) {
451             MUTEX_UNLOCK(MgMUTEXP(mg));
452             croak("cond_signal for lock that we don't own\n");
453         }
454         COND_SIGNAL(MgCONDP(mg));
455         MUTEX_UNLOCK(MgMUTEXP(mg));
456 #endif
457
458 void
459 cond_broadcast(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_L(PerlIO_printf(PerlIO_stderr(), "%p: cond_broadcast %p\n",
469                               thr, sv));
470         MUTEX_LOCK(MgMUTEXP(mg));
471         if (MgOWNER(mg) != thr) {
472             MUTEX_UNLOCK(MgMUTEXP(mg));
473             croak("cond_broadcast for lock that we don't own\n");
474         }
475         COND_BROADCAST(MgCONDP(mg));
476         MUTEX_UNLOCK(MgMUTEXP(mg));
477 #endif
478
479 void
480 list(Class)
481         char *  Class
482     PREINIT:
483         Thread  t;
484         AV *    av;
485         SV **   svp;
486         int     n = 0;
487     PPCODE:
488 #ifdef USE_THREADS
489         av = newAV();
490         /*
491          * Iterate until we have enough dynamic storage for all threads.
492          * We mustn't do any allocation while holding threads_mutex though.
493          */
494         MUTEX_LOCK(&threads_mutex);
495         do {
496             n = nthreads;
497             MUTEX_UNLOCK(&threads_mutex);
498             if (AvFILL(av) < n - 1) {
499                 int i = AvFILL(av);
500                 for (i = AvFILL(av); i < n - 1; i++) {
501                     SV *sv = newSViv(0);        /* fill in tid later */
502                     sv_magic(sv, 0, '~', 0, 0); /* fill in other magic later */
503                     av_push(av, sv_bless(newRV_noinc(sv),
504                                          gv_stashpv(Class, TRUE)));
505         
506                 }
507             }
508             MUTEX_LOCK(&threads_mutex);
509         } while (n < nthreads);
510         n = nthreads;   /* Get the final correct value */
511
512         /*
513          * At this point, there's enough room to fill in av.
514          * Note that we are holding threads_mutex so the list
515          * won't change out from under us but all the remaining
516          * processing is "fast" (no blocking, malloc etc.)
517          */
518         t = thr;
519         svp = AvARRAY(av);
520         do {
521             SV *sv = (SV*)SvRV(*svp);
522             sv_setiv(sv, t->tid);
523             SvMAGIC(sv)->mg_obj = SvREFCNT_inc(t->Toursv);
524             SvMAGIC(sv)->mg_flags |= MGf_REFCOUNTED;
525             SvMAGIC(sv)->mg_private = Thread_MAGIC_SIGNATURE;
526             t = t->next;
527             svp++;
528         } while (t != thr);
529         /*  */
530         MUTEX_UNLOCK(&threads_mutex);
531         /* Truncate any unneeded slots in av */
532         av_fill(av, n - 1);
533         /* Finally, push all the new objects onto the stack and drop av */
534         EXTEND(sp, n);
535         for (svp = AvARRAY(av); n > 0; n--, svp++)
536             PUSHs(*svp);
537         (void)sv_2mortal((SV*)av);
538 #endif
539
540
541 MODULE = Thread         PACKAGE = Thread::Signal
542
543 void
544 kill_sighandler_thread()
545     PPCODE:
546         write(sig_pipe[0], "\0", 1);
547         PUSHs(&sv_yes);
548
549 void
550 init_thread_signals()
551     PPCODE:
552         sighandlerp = handle_thread_signal;
553         if (pipe(sig_pipe) == -1)
554             XSRETURN_UNDEF;
555         PUSHs(&sv_yes);
556
557 SV *
558 await_signal()
559     PREINIT:
560         char c;
561         SSize_t ret;
562     CODE:
563         do {
564             ret = read(sig_pipe[1], &c, 1);
565         } while (ret == -1 && errno == EINTR);
566         if (ret == -1)
567             croak("panic: await_signal");
568         if (ret == 0)
569             XSRETURN_UNDEF;
570         RETVAL = c ? psig_ptr[c] : &sv_no;
571     OUTPUT:
572         RETVAL