Half way through moving per-thread magicals into per-thread fields
[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
8static U32 threadnum = 0;
85ced67f 9static int sig_pipe[2];
683929b4 10
7d901afa 11static void
12remove_thread(t)
13Thread t;
14{
15 DEBUG_L(WITH_THR(PerlIO_printf(PerlIO_stderr(),
16 "%p: remove_thread %p\n", thr, t)));
17 MUTEX_LOCK(&threads_mutex);
0a00ffdb 18 MUTEX_DESTROY(&t->mutex);
7d901afa 19 nthreads--;
20 t->prev->next = t->next;
21 t->next->prev = t->prev;
22 COND_BROADCAST(&nthreads_cond);
23 MUTEX_UNLOCK(&threads_mutex);
24}
25
ea0efc06 26static THREAD_RET_TYPE
d9bb3666 27threadstart(arg)
28void *arg;
29{
783070da 30#ifdef FAKE_THREADS
31 Thread savethread = thr;
32 LOGOP myop;
33 dSP;
34 I32 oldscope = scopestack_ix;
35 I32 retval;
50112d62 36 AV *returnav;
783070da 37 int i;
38
683929b4 39 DEBUG_L(PerlIO_printf(PerlIO_stderr(), "new thread %p starting at %s\n",
40 thr, SvPEEK(TOPs)));
783070da 41 thr = (Thread) arg;
42 savemark = TOPMARK;
43 thr->prev = thr->prev_run = savethread;
44 thr->next = savethread->next;
45 thr->next_run = savethread->next_run;
46 savethread->next = savethread->next_run = thr;
47 thr->wait_queue = 0;
48 thr->private = 0;
49
50 /* Now duplicate most of perl_call_sv but with a few twists */
51 op = (OP*)&myop;
52 Zero(op, 1, LOGOP);
53 myop.op_flags = OPf_STACKED;
54 myop.op_next = Nullop;
55 myop.op_flags |= OPf_KNOW;
56 myop.op_flags |= OPf_WANT_LIST;
57 op = pp_entersub(ARGS);
58 DEBUG_L(if (!op)
59 PerlIO_printf(PerlIO_stderr(), "thread starts at Nullop\n"));
60 /*
61 * When this thread is next scheduled, we start in the right
62 * place. When the thread runs off the end of the sub, perl.c
63 * handles things, using savemark to figure out how much of the
64 * stack is the return value for any join.
65 */
66 thr = savethread; /* back to the old thread */
67 return 0;
68#else
d9bb3666 69 Thread thr = (Thread) arg;
70 LOGOP myop;
71 dSP;
72 I32 oldmark = TOPMARK;
73 I32 oldscope = scopestack_ix;
74 I32 retval;
50112d62 75 AV *returnav;
14fcddff 76 int i, ret;
783070da 77 dJMPENV;
783070da 78
79 /* Don't call *anything* requiring dTHR until after pthread_setspecific */
d9bb3666 80 /*
81 * Wait until our creator releases us. If we didn't do this, then
82 * it would be potentially possible for out thread to carry on and
83 * do stuff before our creator fills in our "self" field. For example,
ea0efc06 84 * if we went and created another thread which tried to JOIN with us,
85 * then we'd be in a mess.
d9bb3666 86 */
50112d62 87 MUTEX_LOCK(&thr->mutex);
88 MUTEX_UNLOCK(&thr->mutex);
d9bb3666 89
d9bb3666 90 /*
91 * It's safe to wait until now to set the thread-specific pointer
92 * from our pthread_t structure to our struct thread, since we're
93 * the only thread who can get at it anyway.
94 */
ea0efc06 95 SET_THR(thr);
d9bb3666 96
783070da 97 /* Only now can we use SvPEEK (which calls sv_newmortal which does dTHR) */
683929b4 98 DEBUG_L(PerlIO_printf(PerlIO_stderr(), "new thread %p starting at %s\n",
99 thr, SvPEEK(TOPs)));
783070da 100
101 JMPENV_PUSH(ret);
102 switch (ret) {
103 case 3:
104 PerlIO_printf(PerlIO_stderr(), "panic: threadstart\n");
d9bb3666 105 /* fall through */
783070da 106 case 1:
107 STATUS_ALL_FAILURE;
d9bb3666 108 /* fall through */
783070da 109 case 2:
110 /* my_exit() was called */
111 while (scopestack_ix > oldscope)
112 LEAVE;
113 JMPENV_POP;
d9bb3666 114 av_store(returnav, 0, newSViv(statusvalue));
115 goto finishoff;
116 }
117
118 /* Now duplicate most of perl_call_sv but with a few twists */
119 op = (OP*)&myop;
120 Zero(op, 1, LOGOP);
121 myop.op_flags = OPf_STACKED;
122 myop.op_next = Nullop;
123 myop.op_flags |= OPf_KNOW;
783070da 124 myop.op_flags |= OPf_WANT_LIST;
d9bb3666 125 op = pp_entersub(ARGS);
126 if (op)
127 runops();
734689b1 128 SPAGAIN;
129 retval = sp - (stack_base + oldmark);
130 sp = stack_base + oldmark + 1;
783070da 131 DEBUG_L(for (i = 1; i <= retval; i++)
132 PerlIO_printf(PerlIO_stderr(),
133 "%p returnav[%d] = %s\n",
134 thr, i, SvPEEK(sp[i - 1]));)
50112d62 135 returnav = newAV();
d9bb3666 136 av_store(returnav, 0, newSVpv("", 0));
734689b1 137 for (i = 1; i <= retval; i++, sp++)
138 sv_setsv(*av_fetch(returnav, i, TRUE), SvREFCNT_inc(*sp));
139
d9bb3666 140 finishoff:
783070da 141#if 0
142 /* removed for debug */
143 SvREFCNT_dec(curstack);
144#endif
d9bb3666 145 SvREFCNT_dec(cvcache);
146 Safefree(markstack);
147 Safefree(scopestack);
148 Safefree(savestack);
149 Safefree(retstack);
150 Safefree(cxstack);
151 Safefree(tmps_stack);
152
14fcddff 153 MUTEX_LOCK(&thr->mutex);
50112d62 154 DEBUG_L(PerlIO_printf(PerlIO_stderr(),
155 "%p: threadstart finishing: state is %u\n",
156 thr, ThrSTATE(thr)));
14fcddff 157 switch (ThrSTATE(thr)) {
158 case THRf_R_JOINABLE:
159 ThrSETSTATE(thr, THRf_ZOMBIE);
160 MUTEX_UNLOCK(&thr->mutex);
783070da 161 DEBUG_L(PerlIO_printf(PerlIO_stderr(),
14fcddff 162 "%p: R_JOINABLE thread finished\n", thr));
163 break;
164 case THRf_R_JOINED:
165 ThrSETSTATE(thr, THRf_DEAD);
166 MUTEX_UNLOCK(&thr->mutex);
50112d62 167 remove_thread(thr);
14fcddff 168 DEBUG_L(PerlIO_printf(PerlIO_stderr(),
169 "%p: R_JOINED thread finished\n", thr));
170 break;
50112d62 171 case THRf_R_DETACHED:
683929b4 172 ThrSETSTATE(thr, THRf_DEAD);
14fcddff 173 MUTEX_UNLOCK(&thr->mutex);
14fcddff 174 SvREFCNT_dec(returnav);
175 DEBUG_L(PerlIO_printf(PerlIO_stderr(),
176 "%p: DETACHED thread finished\n", thr));
50112d62 177 remove_thread(thr); /* This might trigger main thread to finish */
14fcddff 178 break;
179 default:
180 MUTEX_UNLOCK(&thr->mutex);
181 croak("panic: illegal state %u at end of threadstart", ThrSTATE(thr));
182 /* NOTREACHED */
734689b1 183 }
ea0efc06 184 return THREAD_RET_CAST(returnav); /* Available for anyone to join with */
185 /* us unless we're detached, in which */
186 /* case noone sees the value anyway. */
783070da 187#endif
d9bb3666 188}
189
683929b4 190static SV *
191newthread(startsv, initargs, class)
d9bb3666 192SV *startsv;
193AV *initargs;
683929b4 194char *class;
d9bb3666 195{
196 dTHR;
197 dSP;
198 Thread savethread;
199 int i;
683929b4 200 SV *sv;
ea0efc06 201 int err;
202#ifndef THREAD_CREATE
f152979c 203 sigset_t fullmask, oldmask;
ea0efc06 204#endif
d9bb3666 205
206 savethread = thr;
a863c7d1 207 thr = new_struct_thread(thr);
d9bb3666 208 init_stacks(ARGS);
209 SPAGAIN;
50112d62 210 DEBUG_L(PerlIO_printf(PerlIO_stderr(),
211 "%p: newthread, tid is %u, preparing stack\n",
212 savethread, thr->tid));
d9bb3666 213 /* The following pushes the arg list and startsv onto the *new* stack */
214 PUSHMARK(sp);
215 /* Could easily speed up the following greatly */
734689b1 216 for (i = 0; i <= AvFILL(initargs); i++)
d9bb3666 217 XPUSHs(SvREFCNT_inc(*av_fetch(initargs, i, FALSE)));
218 XPUSHs(SvREFCNT_inc(startsv));
219 PUTBACK;
220
ea0efc06 221#ifdef THREAD_CREATE
222 THREAD_CREATE(thr, threadstart);
783070da 223#else
d9bb3666 224 /* On your marks... */
14fcddff 225 MUTEX_LOCK(&thr->mutex);
ea0efc06 226 /* Get set... */
f152979c 227 sigfillset(&fullmask);
228 if (sigprocmask(SIG_SETMASK, &fullmask, &oldmask) == -1)
229 croak("panic: sigprocmask");
46930d8f 230 err = pthread_create(&thr->self, pthread_attr_default,
231 threadstart, (void*) thr);
d9bb3666 232 /* Go */
14fcddff 233 MUTEX_UNLOCK(&thr->mutex);
ea0efc06 234#endif
235 if (err) {
236 /* Thread creation failed--clean up */
237 SvREFCNT_dec(cvcache);
238 remove_thread(thr);
239 MUTEX_DESTROY(&thr->mutex);
240 for (i = 0; i <= AvFILL(initargs); i++)
241 SvREFCNT_dec(*av_fetch(initargs, i, FALSE));
242 SvREFCNT_dec(startsv);
243 return NULL;
244 }
245#ifdef THREAD_POST_CREATE
246 THREAD_POST_CREATE(thr);
247#else
f152979c 248 if (sigprocmask(SIG_SETMASK, &oldmask, 0))
249 croak("panic: sigprocmask");
783070da 250#endif
7d901afa 251 sv = newSViv(thr->tid);
683929b4 252 sv_magic(sv, oursv, '~', 0, 0);
7d901afa 253 SvMAGIC(sv)->mg_private = Thread_MAGIC_SIGNATURE;
254 return sv_bless(newRV_noinc(sv), gv_stashpv(class, TRUE));
d9bb3666 255}
256
f152979c 257static Signal_t
258handle_thread_signal(sig)
259int sig;
260{
261 char c = (char) sig;
262 write(sig_pipe[0], &c, 1);
263}
264
d9bb3666 265MODULE = Thread PACKAGE = Thread
266
683929b4 267void
d9bb3666 268new(class, startsv, ...)
683929b4 269 char * class
d9bb3666 270 SV * startsv
734689b1 271 AV * av = av_make(items - 2, &ST(2));
683929b4 272 PPCODE:
273 XPUSHs(sv_2mortal(newthread(startsv, av, class)));
d9bb3666 274
275void
d9bb3666 276join(t)
277 Thread t
278 AV * av = NO_INIT
279 int i = NO_INIT
280 PPCODE:
7d901afa 281 DEBUG_L(PerlIO_printf(PerlIO_stderr(), "%p: joining %p (state %u)\n",
282 thr, t, ThrSTATE(t)););
50112d62 283 MUTEX_LOCK(&t->mutex);
284 switch (ThrSTATE(t)) {
14fcddff 285 case THRf_R_JOINABLE:
286 case THRf_R_JOINED:
50112d62 287 ThrSETSTATE(t, THRf_R_JOINED);
288 MUTEX_UNLOCK(&t->mutex);
14fcddff 289 break;
290 case THRf_ZOMBIE:
50112d62 291 ThrSETSTATE(t, THRf_DEAD);
292 MUTEX_UNLOCK(&t->mutex);
293 remove_thread(t);
14fcddff 294 break;
295 default:
50112d62 296 MUTEX_UNLOCK(&t->mutex);
14fcddff 297 croak("can't join with thread");
298 /* NOTREACHED */
299 }
ea0efc06 300 JOIN(t, &av);
7d901afa 301
d9bb3666 302 /* Could easily speed up the following if necessary */
303 for (i = 0; i <= AvFILL(av); i++)
304 XPUSHs(sv_2mortal(*av_fetch(av, i, FALSE)));
305
306void
734689b1 307detach(t)
d9bb3666 308 Thread t
309 CODE:
7d901afa 310 DEBUG_L(PerlIO_printf(PerlIO_stderr(), "%p: detaching %p (state %u)\n",
311 thr, t, ThrSTATE(t)););
50112d62 312 MUTEX_LOCK(&t->mutex);
313 switch (ThrSTATE(t)) {
14fcddff 314 case THRf_R_JOINABLE:
50112d62 315 ThrSETSTATE(t, THRf_R_DETACHED);
14fcddff 316 /* fall through */
50112d62 317 case THRf_R_DETACHED:
14fcddff 318 DETACH(t);
50112d62 319 MUTEX_UNLOCK(&t->mutex);
14fcddff 320 break;
321 case THRf_ZOMBIE:
50112d62 322 ThrSETSTATE(t, THRf_DEAD);
7d901afa 323 DETACH(t);
50112d62 324 MUTEX_UNLOCK(&t->mutex);
325 remove_thread(t);
14fcddff 326 break;
327 default:
50112d62 328 MUTEX_UNLOCK(&t->mutex);
14fcddff 329 croak("can't detach thread");
330 /* NOTREACHED */
734689b1 331 }
d9bb3666 332
333void
7d901afa 334equal(t1, t2)
335 Thread t1
336 Thread t2
337 PPCODE:
338 PUSHs((t1 == t2) ? &sv_yes : &sv_no);
339
340void
341flags(t)
342 Thread t
343 PPCODE:
344 PUSHs(sv_2mortal(newSViv(t->flags)));
345
346void
347self(class)
348 char * class
349 PREINIT:
350 SV *sv;
351 PPCODE:
352 sv = newSViv(thr->tid);
353 sv_magic(sv, oursv, '~', 0, 0);
354 SvMAGIC(sv)->mg_private = Thread_MAGIC_SIGNATURE;
355 PUSHs(sv_2mortal(sv_bless(newRV_noinc(sv), gv_stashpv(class, TRUE))));
356
50112d62 357U32
358tid(t)
359 Thread t
360 CODE:
361 MUTEX_LOCK(&t->mutex);
362 RETVAL = t->tid;
363 MUTEX_UNLOCK(&t->mutex);
364 OUTPUT:
365 RETVAL
366
367void
368DESTROY(t)
369 SV * t
370 PPCODE:
371 PUSHs(&sv_yes);
372
7d901afa 373void
734689b1 374yield()
d9bb3666 375 CODE:
ea0efc06 376 YIELD;
d9bb3666 377
378void
734689b1 379cond_wait(sv)
380 SV * sv
381 MAGIC * mg = NO_INIT
382CODE:
2c127b02 383 if (SvROK(sv))
734689b1 384 sv = SvRV(sv);
2c127b02 385
734689b1 386 mg = condpair_magic(sv);
683929b4 387 DEBUG_L(PerlIO_printf(PerlIO_stderr(), "%p: cond_wait %p\n", thr, sv));
734689b1 388 MUTEX_LOCK(MgMUTEXP(mg));
389 if (MgOWNER(mg) != thr) {
390 MUTEX_UNLOCK(MgMUTEXP(mg));
391 croak("cond_wait for lock that we don't own\n");
392 }
393 MgOWNER(mg) = 0;
394 COND_WAIT(MgCONDP(mg), MgMUTEXP(mg));
50112d62 395 while (MgOWNER(mg))
396 COND_WAIT(MgOWNERCONDP(mg), MgMUTEXP(mg));
734689b1 397 MgOWNER(mg) = thr;
398 MUTEX_UNLOCK(MgMUTEXP(mg));
399
400void
401cond_signal(sv)
402 SV * sv
403 MAGIC * mg = NO_INIT
404CODE:
50112d62 405 if (SvROK(sv))
734689b1 406 sv = SvRV(sv);
50112d62 407
734689b1 408 mg = condpair_magic(sv);
683929b4 409 DEBUG_L(PerlIO_printf(PerlIO_stderr(), "%p: cond_signal %p\n",thr,sv));
734689b1 410 MUTEX_LOCK(MgMUTEXP(mg));
411 if (MgOWNER(mg) != thr) {
412 MUTEX_UNLOCK(MgMUTEXP(mg));
413 croak("cond_signal for lock that we don't own\n");
414 }
415 COND_SIGNAL(MgCONDP(mg));
416 MUTEX_UNLOCK(MgMUTEXP(mg));
d9bb3666 417
734689b1 418void
419cond_broadcast(sv)
420 SV * sv
421 MAGIC * mg = NO_INIT
422CODE:
783070da 423 if (SvROK(sv))
734689b1 424 sv = SvRV(sv);
783070da 425
734689b1 426 mg = condpair_magic(sv);
683929b4 427 DEBUG_L(PerlIO_printf(PerlIO_stderr(), "%p: cond_broadcast %p\n",
428 thr, sv));
734689b1 429 MUTEX_LOCK(MgMUTEXP(mg));
430 if (MgOWNER(mg) != thr) {
431 MUTEX_UNLOCK(MgMUTEXP(mg));
432 croak("cond_broadcast for lock that we don't own\n");
433 }
434 COND_BROADCAST(MgCONDP(mg));
435 MUTEX_UNLOCK(MgMUTEXP(mg));
f152979c 436
7d901afa 437void
438list(class)
439 char * class
440 PREINIT:
441 Thread t;
442 AV * av;
443 SV ** svp;
444 int n = 0;
445 PPCODE:
446 av = newAV();
447 /*
448 * Iterate until we have enough dynamic storage for all threads.
449 * We mustn't do any allocation while holding threads_mutex though.
450 */
451 MUTEX_LOCK(&threads_mutex);
452 do {
453 n = nthreads;
454 MUTEX_UNLOCK(&threads_mutex);
455 if (AvFILL(av) < n - 1) {
456 int i = AvFILL(av);
457 for (i = AvFILL(av); i < n - 1; i++) {
458 SV *sv = newSViv(0); /* fill in tid later */
459 sv_magic(sv, 0, '~', 0, 0); /* fill in other magic later */
460 av_push(av, sv_bless(newRV_noinc(sv),
461 gv_stashpv(class, TRUE)));
50112d62 462
7d901afa 463 }
464 }
465 MUTEX_LOCK(&threads_mutex);
466 } while (n < nthreads);
50112d62 467 n = nthreads; /* Get the final correct value */
7d901afa 468
469 /*
470 * At this point, there's enough room to fill in av.
471 * Note that we are holding threads_mutex so the list
472 * won't change out from under us but all the remaining
473 * processing is "fast" (no blocking, malloc etc.)
474 */
475 t = thr;
476 svp = AvARRAY(av);
477 do {
0a00ffdb 478 SV *sv = (SV*)SvRV(*svp);
7d901afa 479 sv_setiv(sv, t->tid);
480 SvMAGIC(sv)->mg_obj = SvREFCNT_inc(t->Toursv);
481 SvMAGIC(sv)->mg_flags |= MGf_REFCOUNTED;
482 SvMAGIC(sv)->mg_private = Thread_MAGIC_SIGNATURE;
483 t = t->next;
0a00ffdb 484 svp++;
7d901afa 485 } while (t != thr);
50112d62 486 /* */
7d901afa 487 MUTEX_UNLOCK(&threads_mutex);
488 /* Truncate any unneeded slots in av */
50112d62 489 av_fill(av, n - 1);
7d901afa 490 /* Finally, push all the new objects onto the stack and drop av */
491 EXTEND(sp, n);
492 for (svp = AvARRAY(av); n > 0; n--, svp++)
493 PUSHs(*svp);
494 (void)sv_2mortal((SV*)av);
495
496
f152979c 497MODULE = Thread PACKAGE = Thread::Signal
498
499void
500kill_sighandler_thread()
501 PPCODE:
502 write(sig_pipe[0], "\0", 1);
503 PUSHs(&sv_yes);
504
505void
506init_thread_signals()
507 PPCODE:
508 sighandlerp = handle_thread_signal;
509 if (pipe(sig_pipe) == -1)
510 XSRETURN_UNDEF;
511 PUSHs(&sv_yes);
512
513SV *
514await_signal()
515 PREINIT:
516 char c;
ea0efc06 517 SSize_t ret;
f152979c 518 CODE:
519 do {
520 ret = read(sig_pipe[1], &c, 1);
521 } while (ret == -1 && errno == EINTR);
522 if (ret == -1)
523 croak("panic: await_signal");
524 if (ret == 0)
525 XSRETURN_UNDEF;
526 RETVAL = c ? psig_ptr[c] : &sv_no;
527 OUTPUT:
528 RETVAL