Integrate (-ay) win32 branch at its creation to
[p5sagit/p5-mst-13.2.git] / ext / Thread / Thread.xs
CommitLineData
d9bb3666 1#include "EXTERN.h"
2#include "perl.h"
3#include "XSUB.h"
4
7d901afa 5/* Magic signature for Thread's mg_private is "Th" */
6#define Thread_MAGIC_SIGNATURE 0x5468
7
f0f333f4 8#ifdef __cplusplus
9#ifdef I_UNISTD
10#include <unistd.h>
11#endif
12#endif
13#include <fcntl.h>
14
7d901afa 15static U32 threadnum = 0;
85ced67f 16static int sig_pipe[2];
f0f333f4 17
18#ifndef THREAD_RET_TYPE
19typedef struct thread *Thread;
20#define THREAD_RET_TYPE void *
21#define THREAD_RET_CAST(x) ((THREAD_RET_TYPE) x)
22#endif;
683929b4 23
7d901afa 24static void
f0f333f4 25remove_thread(struct thread *t)
7d901afa 26{
f0f333f4 27#ifdef USE_THREADS
7d901afa 28 DEBUG_L(WITH_THR(PerlIO_printf(PerlIO_stderr(),
29 "%p: remove_thread %p\n", thr, t)));
30 MUTEX_LOCK(&threads_mutex);
0a00ffdb 31 MUTEX_DESTROY(&t->mutex);
7d901afa 32 nthreads--;
33 t->prev->next = t->next;
34 t->next->prev = t->prev;
35 COND_BROADCAST(&nthreads_cond);
36 MUTEX_UNLOCK(&threads_mutex);
f0f333f4 37#endif
7d901afa 38}
39
ea0efc06 40static THREAD_RET_TYPE
f0f333f4 41threadstart(void *arg)
d9bb3666 42{
f0f333f4 43#ifdef USE_THREADS
783070da 44#ifdef FAKE_THREADS
45 Thread savethread = thr;
46 LOGOP myop;
47 dSP;
48 I32 oldscope = scopestack_ix;
49 I32 retval;
50112d62 50 AV *returnav;
783070da 51 int i;
52
683929b4 53 DEBUG_L(PerlIO_printf(PerlIO_stderr(), "new thread %p starting at %s\n",
54 thr, SvPEEK(TOPs)));
783070da 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
d9bb3666 83 Thread thr = (Thread) arg;
84 LOGOP myop;
4e35701f 85 djSP;
d9bb3666 86 I32 oldmark = TOPMARK;
87 I32 oldscope = scopestack_ix;
88 I32 retval;
50112d62 89 AV *returnav;
14fcddff 90 int i, ret;
783070da 91 dJMPENV;
0b9678a8 92 DEBUG_L(PerlIO_printf(PerlIO_stderr(), "new thread %p waiting to start\n",
93 thr));
783070da 94
0b9678a8 95 /* Don't call *anything* requiring dTHR until after SET_THR() */
d9bb3666 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,
ea0efc06 100 * if we went and created another thread which tried to JOIN with us,
101 * then we'd be in a mess.
d9bb3666 102 */
50112d62 103 MUTEX_LOCK(&thr->mutex);
104 MUTEX_UNLOCK(&thr->mutex);
d9bb3666 105
d9bb3666 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 */
ea0efc06 111 SET_THR(thr);
d9bb3666 112
783070da 113 /* Only now can we use SvPEEK (which calls sv_newmortal which does dTHR) */
683929b4 114 DEBUG_L(PerlIO_printf(PerlIO_stderr(), "new thread %p starting at %s\n",
115 thr, SvPEEK(TOPs)));
783070da 116
117 JMPENV_PUSH(ret);
118 switch (ret) {
119 case 3:
120 PerlIO_printf(PerlIO_stderr(), "panic: threadstart\n");
d9bb3666 121 /* fall through */
783070da 122 case 1:
123 STATUS_ALL_FAILURE;
d9bb3666 124 /* fall through */
783070da 125 case 2:
126 /* my_exit() was called */
127 while (scopestack_ix > oldscope)
128 LEAVE;
129 JMPENV_POP;
d9bb3666 130 av_store(returnav, 0, newSViv(statusvalue));
131 goto finishoff;
132 }
133
199100c8 134 CATCH_SET(TRUE);
135
d9bb3666 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;
783070da 142 myop.op_flags |= OPf_WANT_LIST;
d9bb3666 143 op = pp_entersub(ARGS);
144 if (op)
145 runops();
734689b1 146 SPAGAIN;
147 retval = sp - (stack_base + oldmark);
148 sp = stack_base + oldmark + 1;
783070da 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]));)
50112d62 153 returnav = newAV();
d9bb3666 154 av_store(returnav, 0, newSVpv("", 0));
734689b1 155 for (i = 1; i <= retval; i++, sp++)
156 sv_setsv(*av_fetch(returnav, i, TRUE), SvREFCNT_inc(*sp));
157
d9bb3666 158 finishoff:
783070da 159#if 0
160 /* removed for debug */
161 SvREFCNT_dec(curstack);
162#endif
199100c8 163 SvREFCNT_dec(thr->cvcache);
554b3eca 164 SvREFCNT_dec(thr->magicals);
165 SvREFCNT_dec(thr->specific);
38a03e6e 166 SvREFCNT_dec(thr->errsv);
167 SvREFCNT_dec(thr->errhv);
d9bb3666 168 Safefree(markstack);
169 Safefree(scopestack);
170 Safefree(savestack);
171 Safefree(retstack);
172 Safefree(cxstack);
173 Safefree(tmps_stack);
199100c8 174 Safefree(ofs);
d9bb3666 175
14fcddff 176 MUTEX_LOCK(&thr->mutex);
50112d62 177 DEBUG_L(PerlIO_printf(PerlIO_stderr(),
178 "%p: threadstart finishing: state is %u\n",
179 thr, ThrSTATE(thr)));
14fcddff 180 switch (ThrSTATE(thr)) {
181 case THRf_R_JOINABLE:
182 ThrSETSTATE(thr, THRf_ZOMBIE);
183 MUTEX_UNLOCK(&thr->mutex);
783070da 184 DEBUG_L(PerlIO_printf(PerlIO_stderr(),
14fcddff 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);
50112d62 190 remove_thread(thr);
14fcddff 191 DEBUG_L(PerlIO_printf(PerlIO_stderr(),
192 "%p: R_JOINED thread finished\n", thr));
193 break;
50112d62 194 case THRf_R_DETACHED:
683929b4 195 ThrSETSTATE(thr, THRf_DEAD);
14fcddff 196 MUTEX_UNLOCK(&thr->mutex);
14fcddff 197 SvREFCNT_dec(returnav);
198 DEBUG_L(PerlIO_printf(PerlIO_stderr(),
199 "%p: DETACHED thread finished\n", thr));
50112d62 200 remove_thread(thr); /* This might trigger main thread to finish */
14fcddff 201 break;
202 default:
203 MUTEX_UNLOCK(&thr->mutex);
204 croak("panic: illegal state %u at end of threadstart", ThrSTATE(thr));
205 /* NOTREACHED */
734689b1 206 }
ea0efc06 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. */
783070da 210#endif
f0f333f4 211#else
212 return THREAD_RET_CAST(NULL);
213#endif
d9bb3666 214}
215
683929b4 216static SV *
f0f333f4 217newthread (SV *startsv, AV *initargs, char *Class)
d9bb3666 218{
f0f333f4 219#ifdef USE_THREADS
d9bb3666 220 dSP;
221 Thread savethread;
222 int i;
683929b4 223 SV *sv;
ea0efc06 224 int err;
225#ifndef THREAD_CREATE
f152979c 226 sigset_t fullmask, oldmask;
ea0efc06 227#endif
d9bb3666 228
229 savethread = thr;
a863c7d1 230 thr = new_struct_thread(thr);
d9bb3666 231 SPAGAIN;
50112d62 232 DEBUG_L(PerlIO_printf(PerlIO_stderr(),
0b9678a8 233 "%p: newthread (%p), tid is %u, preparing stack\n",
234 savethread, thr, thr->tid));
d9bb3666 235 /* The following pushes the arg list and startsv onto the *new* stack */
236 PUSHMARK(sp);
237 /* Could easily speed up the following greatly */
734689b1 238 for (i = 0; i <= AvFILL(initargs); i++)
d9bb3666 239 XPUSHs(SvREFCNT_inc(*av_fetch(initargs, i, FALSE)));
240 XPUSHs(SvREFCNT_inc(startsv));
241 PUTBACK;
ea0efc06 242#ifdef THREAD_CREATE
f0f333f4 243 err = THREAD_CREATE(thr, threadstart);
783070da 244#else
d9bb3666 245 /* On your marks... */
14fcddff 246 MUTEX_LOCK(&thr->mutex);
ea0efc06 247 /* Get set... */
f152979c 248 sigfillset(&fullmask);
249 if (sigprocmask(SIG_SETMASK, &fullmask, &oldmask) == -1)
250 croak("panic: sigprocmask");
46930d8f 251 err = pthread_create(&thr->self, pthread_attr_default,
252 threadstart, (void*) thr);
d9bb3666 253 /* Go */
14fcddff 254 MUTEX_UNLOCK(&thr->mutex);
ea0efc06 255#endif
256 if (err) {
0b9678a8 257 DEBUG_L(PerlIO_printf(PerlIO_stderr(),
258 "%p: create of %p failed %d\n", savethread, thr, err));
ea0efc06 259 /* Thread creation failed--clean up */
199100c8 260 SvREFCNT_dec(thr->cvcache);
ea0efc06 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
f152979c 271 if (sigprocmask(SIG_SETMASK, &oldmask, 0))
272 croak("panic: sigprocmask");
783070da 273#endif
7d901afa 274 sv = newSViv(thr->tid);
199100c8 275 sv_magic(sv, thr->oursv, '~', 0, 0);
7d901afa 276 SvMAGIC(sv)->mg_private = Thread_MAGIC_SIGNATURE;
f0f333f4 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
d9bb3666 282}
283
f0f333f4 284static Signal_t handle_thread_signal _((int sig));
285
f152979c 286static Signal_t
f0f333f4 287handle_thread_signal(int sig)
f152979c 288{
289 char c = (char) sig;
290 write(sig_pipe[0], &c, 1);
291}
292
d9bb3666 293MODULE = Thread PACKAGE = Thread
0b9678a8 294PROTOTYPES: DISABLE
d9bb3666 295
683929b4 296void
f0f333f4 297new(Class, startsv, ...)
298 char * Class
d9bb3666 299 SV * startsv
734689b1 300 AV * av = av_make(items - 2, &ST(2));
683929b4 301 PPCODE:
f0f333f4 302 XPUSHs(sv_2mortal(newthread(startsv, av, Class)));
d9bb3666 303
304void
d9bb3666 305join(t)
306 Thread t
307 AV * av = NO_INIT
308 int i = NO_INIT
309 PPCODE:
f0f333f4 310#ifdef USE_THREADS
7d901afa 311 DEBUG_L(PerlIO_printf(PerlIO_stderr(), "%p: joining %p (state %u)\n",
312 thr, t, ThrSTATE(t)););
50112d62 313 MUTEX_LOCK(&t->mutex);
314 switch (ThrSTATE(t)) {
14fcddff 315 case THRf_R_JOINABLE:
316 case THRf_R_JOINED:
50112d62 317 ThrSETSTATE(t, THRf_R_JOINED);
318 MUTEX_UNLOCK(&t->mutex);
14fcddff 319 break;
320 case THRf_ZOMBIE:
50112d62 321 ThrSETSTATE(t, THRf_DEAD);
322 MUTEX_UNLOCK(&t->mutex);
323 remove_thread(t);
14fcddff 324 break;
325 default:
50112d62 326 MUTEX_UNLOCK(&t->mutex);
14fcddff 327 croak("can't join with thread");
328 /* NOTREACHED */
329 }
ea0efc06 330 JOIN(t, &av);
7d901afa 331
d9bb3666 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)));
f0f333f4 335#endif
d9bb3666 336
337void
734689b1 338detach(t)
d9bb3666 339 Thread t
340 CODE:
f0f333f4 341#ifdef USE_THREADS
7d901afa 342 DEBUG_L(PerlIO_printf(PerlIO_stderr(), "%p: detaching %p (state %u)\n",
343 thr, t, ThrSTATE(t)););
50112d62 344 MUTEX_LOCK(&t->mutex);
345 switch (ThrSTATE(t)) {
14fcddff 346 case THRf_R_JOINABLE:
50112d62 347 ThrSETSTATE(t, THRf_R_DETACHED);
14fcddff 348 /* fall through */
50112d62 349 case THRf_R_DETACHED:
14fcddff 350 DETACH(t);
50112d62 351 MUTEX_UNLOCK(&t->mutex);
14fcddff 352 break;
353 case THRf_ZOMBIE:
50112d62 354 ThrSETSTATE(t, THRf_DEAD);
7d901afa 355 DETACH(t);
50112d62 356 MUTEX_UNLOCK(&t->mutex);
357 remove_thread(t);
14fcddff 358 break;
359 default:
50112d62 360 MUTEX_UNLOCK(&t->mutex);
14fcddff 361 croak("can't detach thread");
362 /* NOTREACHED */
734689b1 363 }
f0f333f4 364#endif
d9bb3666 365
366void
7d901afa 367equal(t1, t2)
368 Thread t1
369 Thread t2
370 PPCODE:
371 PUSHs((t1 == t2) ? &sv_yes : &sv_no);
372
373void
374flags(t)
375 Thread t
376 PPCODE:
f0f333f4 377#ifdef USE_THREADS
7d901afa 378 PUSHs(sv_2mortal(newSViv(t->flags)));
f0f333f4 379#endif
7d901afa 380
381void
f0f333f4 382self(Class)
383 char * Class
7d901afa 384 PREINIT:
385 SV *sv;
f0f333f4 386 PPCODE:
387#ifdef USE_THREADS
7d901afa 388 sv = newSViv(thr->tid);
199100c8 389 sv_magic(sv, thr->oursv, '~', 0, 0);
7d901afa 390 SvMAGIC(sv)->mg_private = Thread_MAGIC_SIGNATURE;
f0f333f4 391 PUSHs(sv_2mortal(sv_bless(newRV_noinc(sv), gv_stashpv(Class, TRUE))));
392#endif
7d901afa 393
50112d62 394U32
395tid(t)
396 Thread t
397 CODE:
f0f333f4 398#ifdef USE_THREADS
50112d62 399 MUTEX_LOCK(&t->mutex);
400 RETVAL = t->tid;
401 MUTEX_UNLOCK(&t->mutex);
f0f333f4 402#else
403 RETVAL = 0;
404#endif
50112d62 405 OUTPUT:
406 RETVAL
407
408void
409DESTROY(t)
410 SV * t
411 PPCODE:
412 PUSHs(&sv_yes);
413
7d901afa 414void
734689b1 415yield()
d9bb3666 416 CODE:
f0f333f4 417{
418#ifdef USE_THREADS
ea0efc06 419 YIELD;
f0f333f4 420#endif
421}
d9bb3666 422
423void
734689b1 424cond_wait(sv)
425 SV * sv
426 MAGIC * mg = NO_INIT
f0f333f4 427CODE:
428#ifdef USE_THREADS
2c127b02 429 if (SvROK(sv))
734689b1 430 sv = SvRV(sv);
2c127b02 431
734689b1 432 mg = condpair_magic(sv);
683929b4 433 DEBUG_L(PerlIO_printf(PerlIO_stderr(), "%p: cond_wait %p\n", thr, sv));
734689b1 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));
50112d62 441 while (MgOWNER(mg))
442 COND_WAIT(MgOWNERCONDP(mg), MgMUTEXP(mg));
734689b1 443 MgOWNER(mg) = thr;
444 MUTEX_UNLOCK(MgMUTEXP(mg));
f0f333f4 445#endif
446
734689b1 447void
448cond_signal(sv)
449 SV * sv
450 MAGIC * mg = NO_INIT
451CODE:
f0f333f4 452#ifdef USE_THREADS
50112d62 453 if (SvROK(sv))
734689b1 454 sv = SvRV(sv);
50112d62 455
734689b1 456 mg = condpair_magic(sv);
683929b4 457 DEBUG_L(PerlIO_printf(PerlIO_stderr(), "%p: cond_signal %p\n",thr,sv));
734689b1 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));
f0f333f4 465#endif
d9bb3666 466
734689b1 467void
468cond_broadcast(sv)
469 SV * sv
470 MAGIC * mg = NO_INIT
f0f333f4 471CODE:
472#ifdef USE_THREADS
783070da 473 if (SvROK(sv))
734689b1 474 sv = SvRV(sv);
783070da 475
734689b1 476 mg = condpair_magic(sv);
683929b4 477 DEBUG_L(PerlIO_printf(PerlIO_stderr(), "%p: cond_broadcast %p\n",
478 thr, sv));
734689b1 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));
f0f333f4 486#endif
f152979c 487
7d901afa 488void
f0f333f4 489list(Class)
490 char * Class
7d901afa 491 PREINIT:
492 Thread t;
493 AV * av;
494 SV ** svp;
495 int n = 0;
496 PPCODE:
f0f333f4 497#ifdef USE_THREADS
7d901afa 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),
f0f333f4 513 gv_stashpv(Class, TRUE)));
50112d62 514
7d901afa 515 }
516 }
517 MUTEX_LOCK(&threads_mutex);
518 } while (n < nthreads);
50112d62 519 n = nthreads; /* Get the final correct value */
7d901afa 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 {
0a00ffdb 530 SV *sv = (SV*)SvRV(*svp);
7d901afa 531 sv_setiv(sv, t->tid);
199100c8 532 SvMAGIC(sv)->mg_obj = SvREFCNT_inc(t->oursv);
7d901afa 533 SvMAGIC(sv)->mg_flags |= MGf_REFCOUNTED;
534 SvMAGIC(sv)->mg_private = Thread_MAGIC_SIGNATURE;
535 t = t->next;
0a00ffdb 536 svp++;
7d901afa 537 } while (t != thr);
50112d62 538 /* */
7d901afa 539 MUTEX_UNLOCK(&threads_mutex);
540 /* Truncate any unneeded slots in av */
50112d62 541 av_fill(av, n - 1);
7d901afa 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);
f0f333f4 547#endif
7d901afa 548
549
f152979c 550MODULE = Thread PACKAGE = Thread::Signal
551
552void
553kill_sighandler_thread()
554 PPCODE:
555 write(sig_pipe[0], "\0", 1);
556 PUSHs(&sv_yes);
557
558void
559init_thread_signals()
560 PPCODE:
561 sighandlerp = handle_thread_signal;
562 if (pipe(sig_pipe) == -1)
563 XSRETURN_UNDEF;
564 PUSHs(&sv_yes);
565
566SV *
567await_signal()
568 PREINIT:
569 char c;
ea0efc06 570 SSize_t ret;
f152979c 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
4e35701f 582