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