This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Per-thread magicals mostly working (and localisable). Now getting
[perl5.git] / ext / Thread / Thread.xs
CommitLineData
d9bb3666
MB
1#include "EXTERN.h"
2#include "perl.h"
3#include "XSUB.h"
4
7d901afa
MB
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
MB
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
MB
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
MB
27threadstart(arg)
28void *arg;
29{
783070da
MB
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
MB
37 int i;
38
683929b4
MB
39 DEBUG_L(PerlIO_printf(PerlIO_stderr(), "new thread %p starting at %s\n",
40 thr, SvPEEK(TOPs)));
783070da
MB
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
MB
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
MB
78
79 /* Don't call *anything* requiring dTHR until after pthread_setspecific */
d9bb3666
MB
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
MB
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
MB
87 MUTEX_LOCK(&thr->mutex);
88 MUTEX_UNLOCK(&thr->mutex);
d9bb3666 89
d9bb3666
MB
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
MB
98 DEBUG_L(PerlIO_printf(PerlIO_stderr(), "new thread %p starting at %s\n",
99 thr, SvPEEK(TOPs)));
783070da
MB
100
101 JMPENV_PUSH(ret);
102 switch (ret) {
103 case 3:
104 PerlIO_printf(PerlIO_stderr(), "panic: threadstart\n");
d9bb3666 105 /* fall through */
783070da
MB
106 case 1:
107 STATUS_ALL_FAILURE;
d9bb3666 108 /* fall through */
783070da
MB
109 case 2:
110 /* my_exit() was called */
111 while (scopestack_ix > oldscope)
112 LEAVE;
113 JMPENV_POP;
d9bb3666
MB
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
MB
125 op = pp_entersub(ARGS);
126 if (op)
127 runops();
734689b1
MB
128 SPAGAIN;
129 retval = sp - (stack_base + oldmark);
130 sp = stack_base + oldmark + 1;
783070da
MB
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
MB
137 for (i = 1; i <= retval; i++, sp++)
138 sv_setsv(*av_fetch(returnav, i, TRUE), SvREFCNT_inc(*sp));
139
d9bb3666 140 finishoff:
783070da
MB
141#if 0
142 /* removed for debug */
143 SvREFCNT_dec(curstack);
144#endif
d9bb3666 145 SvREFCNT_dec(cvcache);
554b3eca
MB
146 SvREFCNT_dec(thr->magicals);
147 SvREFCNT_dec(thr->specific);
d9bb3666
MB
148 Safefree(markstack);
149 Safefree(scopestack);
150 Safefree(savestack);
151 Safefree(retstack);
152 Safefree(cxstack);
153 Safefree(tmps_stack);
154
14fcddff 155 MUTEX_LOCK(&thr->mutex);
50112d62
MB
156 DEBUG_L(PerlIO_printf(PerlIO_stderr(),
157 "%p: threadstart finishing: state is %u\n",
158 thr, ThrSTATE(thr)));
14fcddff
MB
159 switch (ThrSTATE(thr)) {
160 case THRf_R_JOINABLE:
161 ThrSETSTATE(thr, THRf_ZOMBIE);
162 MUTEX_UNLOCK(&thr->mutex);
783070da 163 DEBUG_L(PerlIO_printf(PerlIO_stderr(),
14fcddff
MB
164 "%p: R_JOINABLE thread finished\n", thr));
165 break;
166 case THRf_R_JOINED:
167 ThrSETSTATE(thr, THRf_DEAD);
168 MUTEX_UNLOCK(&thr->mutex);
50112d62 169 remove_thread(thr);
14fcddff
MB
170 DEBUG_L(PerlIO_printf(PerlIO_stderr(),
171 "%p: R_JOINED thread finished\n", thr));
172 break;
50112d62 173 case THRf_R_DETACHED:
683929b4 174 ThrSETSTATE(thr, THRf_DEAD);
14fcddff 175 MUTEX_UNLOCK(&thr->mutex);
14fcddff
MB
176 SvREFCNT_dec(returnav);
177 DEBUG_L(PerlIO_printf(PerlIO_stderr(),
178 "%p: DETACHED thread finished\n", thr));
50112d62 179 remove_thread(thr); /* This might trigger main thread to finish */
14fcddff
MB
180 break;
181 default:
182 MUTEX_UNLOCK(&thr->mutex);
183 croak("panic: illegal state %u at end of threadstart", ThrSTATE(thr));
184 /* NOTREACHED */
734689b1 185 }
ea0efc06
MB
186 return THREAD_RET_CAST(returnav); /* Available for anyone to join with */
187 /* us unless we're detached, in which */
188 /* case noone sees the value anyway. */
783070da 189#endif
d9bb3666
MB
190}
191
683929b4
MB
192static SV *
193newthread(startsv, initargs, class)
d9bb3666
MB
194SV *startsv;
195AV *initargs;
683929b4 196char *class;
d9bb3666
MB
197{
198 dTHR;
199 dSP;
200 Thread savethread;
201 int i;
683929b4 202 SV *sv;
ea0efc06
MB
203 int err;
204#ifndef THREAD_CREATE
f152979c 205 sigset_t fullmask, oldmask;
ea0efc06 206#endif
d9bb3666
MB
207
208 savethread = thr;
a863c7d1 209 thr = new_struct_thread(thr);
d9bb3666
MB
210 init_stacks(ARGS);
211 SPAGAIN;
50112d62
MB
212 DEBUG_L(PerlIO_printf(PerlIO_stderr(),
213 "%p: newthread, tid is %u, preparing stack\n",
214 savethread, thr->tid));
d9bb3666
MB
215 /* The following pushes the arg list and startsv onto the *new* stack */
216 PUSHMARK(sp);
217 /* Could easily speed up the following greatly */
734689b1 218 for (i = 0; i <= AvFILL(initargs); i++)
d9bb3666
MB
219 XPUSHs(SvREFCNT_inc(*av_fetch(initargs, i, FALSE)));
220 XPUSHs(SvREFCNT_inc(startsv));
221 PUTBACK;
222
ea0efc06
MB
223#ifdef THREAD_CREATE
224 THREAD_CREATE(thr, threadstart);
783070da 225#else
d9bb3666 226 /* On your marks... */
14fcddff 227 MUTEX_LOCK(&thr->mutex);
ea0efc06 228 /* Get set... */
f152979c
MB
229 sigfillset(&fullmask);
230 if (sigprocmask(SIG_SETMASK, &fullmask, &oldmask) == -1)
231 croak("panic: sigprocmask");
46930d8f
MB
232 err = pthread_create(&thr->self, pthread_attr_default,
233 threadstart, (void*) thr);
d9bb3666 234 /* Go */
14fcddff 235 MUTEX_UNLOCK(&thr->mutex);
ea0efc06
MB
236#endif
237 if (err) {
238 /* Thread creation failed--clean up */
239 SvREFCNT_dec(cvcache);
240 remove_thread(thr);
241 MUTEX_DESTROY(&thr->mutex);
242 for (i = 0; i <= AvFILL(initargs); i++)
243 SvREFCNT_dec(*av_fetch(initargs, i, FALSE));
244 SvREFCNT_dec(startsv);
245 return NULL;
246 }
247#ifdef THREAD_POST_CREATE
248 THREAD_POST_CREATE(thr);
249#else
f152979c
MB
250 if (sigprocmask(SIG_SETMASK, &oldmask, 0))
251 croak("panic: sigprocmask");
783070da 252#endif
7d901afa 253 sv = newSViv(thr->tid);
683929b4 254 sv_magic(sv, oursv, '~', 0, 0);
7d901afa
MB
255 SvMAGIC(sv)->mg_private = Thread_MAGIC_SIGNATURE;
256 return sv_bless(newRV_noinc(sv), gv_stashpv(class, TRUE));
d9bb3666
MB
257}
258
f152979c
MB
259static Signal_t
260handle_thread_signal(sig)
261int sig;
262{
263 char c = (char) sig;
264 write(sig_pipe[0], &c, 1);
265}
266
d9bb3666
MB
267MODULE = Thread PACKAGE = Thread
268
683929b4 269void
d9bb3666 270new(class, startsv, ...)
683929b4 271 char * class
d9bb3666 272 SV * startsv
734689b1 273 AV * av = av_make(items - 2, &ST(2));
683929b4
MB
274 PPCODE:
275 XPUSHs(sv_2mortal(newthread(startsv, av, class)));
d9bb3666
MB
276
277void
d9bb3666
MB
278join(t)
279 Thread t
280 AV * av = NO_INIT
281 int i = NO_INIT
282 PPCODE:
7d901afa
MB
283 DEBUG_L(PerlIO_printf(PerlIO_stderr(), "%p: joining %p (state %u)\n",
284 thr, t, ThrSTATE(t)););
50112d62
MB
285 MUTEX_LOCK(&t->mutex);
286 switch (ThrSTATE(t)) {
14fcddff
MB
287 case THRf_R_JOINABLE:
288 case THRf_R_JOINED:
50112d62
MB
289 ThrSETSTATE(t, THRf_R_JOINED);
290 MUTEX_UNLOCK(&t->mutex);
14fcddff
MB
291 break;
292 case THRf_ZOMBIE:
50112d62
MB
293 ThrSETSTATE(t, THRf_DEAD);
294 MUTEX_UNLOCK(&t->mutex);
295 remove_thread(t);
14fcddff
MB
296 break;
297 default:
50112d62 298 MUTEX_UNLOCK(&t->mutex);
14fcddff
MB
299 croak("can't join with thread");
300 /* NOTREACHED */
301 }
ea0efc06 302 JOIN(t, &av);
7d901afa 303
d9bb3666
MB
304 /* Could easily speed up the following if necessary */
305 for (i = 0; i <= AvFILL(av); i++)
306 XPUSHs(sv_2mortal(*av_fetch(av, i, FALSE)));
307
308void
734689b1 309detach(t)
d9bb3666
MB
310 Thread t
311 CODE:
7d901afa
MB
312 DEBUG_L(PerlIO_printf(PerlIO_stderr(), "%p: detaching %p (state %u)\n",
313 thr, t, ThrSTATE(t)););
50112d62
MB
314 MUTEX_LOCK(&t->mutex);
315 switch (ThrSTATE(t)) {
14fcddff 316 case THRf_R_JOINABLE:
50112d62 317 ThrSETSTATE(t, THRf_R_DETACHED);
14fcddff 318 /* fall through */
50112d62 319 case THRf_R_DETACHED:
14fcddff 320 DETACH(t);
50112d62 321 MUTEX_UNLOCK(&t->mutex);
14fcddff
MB
322 break;
323 case THRf_ZOMBIE:
50112d62 324 ThrSETSTATE(t, THRf_DEAD);
7d901afa 325 DETACH(t);
50112d62
MB
326 MUTEX_UNLOCK(&t->mutex);
327 remove_thread(t);
14fcddff
MB
328 break;
329 default:
50112d62 330 MUTEX_UNLOCK(&t->mutex);
14fcddff
MB
331 croak("can't detach thread");
332 /* NOTREACHED */
734689b1 333 }
d9bb3666
MB
334
335void
7d901afa
MB
336equal(t1, t2)
337 Thread t1
338 Thread t2
339 PPCODE:
340 PUSHs((t1 == t2) ? &sv_yes : &sv_no);
341
342void
343flags(t)
344 Thread t
345 PPCODE:
346 PUSHs(sv_2mortal(newSViv(t->flags)));
347
348void
349self(class)
350 char * class
351 PREINIT:
352 SV *sv;
353 PPCODE:
354 sv = newSViv(thr->tid);
355 sv_magic(sv, oursv, '~', 0, 0);
356 SvMAGIC(sv)->mg_private = Thread_MAGIC_SIGNATURE;
357 PUSHs(sv_2mortal(sv_bless(newRV_noinc(sv), gv_stashpv(class, TRUE))));
358
50112d62
MB
359U32
360tid(t)
361 Thread t
362 CODE:
363 MUTEX_LOCK(&t->mutex);
364 RETVAL = t->tid;
365 MUTEX_UNLOCK(&t->mutex);
366 OUTPUT:
367 RETVAL
368
369void
370DESTROY(t)
371 SV * t
372 PPCODE:
373 PUSHs(&sv_yes);
374
7d901afa 375void
734689b1 376yield()
d9bb3666 377 CODE:
ea0efc06 378 YIELD;
d9bb3666
MB
379
380void
734689b1
MB
381cond_wait(sv)
382 SV * sv
383 MAGIC * mg = NO_INIT
384CODE:
2c127b02 385 if (SvROK(sv))
734689b1 386 sv = SvRV(sv);
2c127b02 387
734689b1 388 mg = condpair_magic(sv);
683929b4 389 DEBUG_L(PerlIO_printf(PerlIO_stderr(), "%p: cond_wait %p\n", thr, sv));
734689b1
MB
390 MUTEX_LOCK(MgMUTEXP(mg));
391 if (MgOWNER(mg) != thr) {
392 MUTEX_UNLOCK(MgMUTEXP(mg));
393 croak("cond_wait for lock that we don't own\n");
394 }
395 MgOWNER(mg) = 0;
396 COND_WAIT(MgCONDP(mg), MgMUTEXP(mg));
50112d62
MB
397 while (MgOWNER(mg))
398 COND_WAIT(MgOWNERCONDP(mg), MgMUTEXP(mg));
734689b1
MB
399 MgOWNER(mg) = thr;
400 MUTEX_UNLOCK(MgMUTEXP(mg));
401
402void
403cond_signal(sv)
404 SV * sv
405 MAGIC * mg = NO_INIT
406CODE:
50112d62 407 if (SvROK(sv))
734689b1 408 sv = SvRV(sv);
50112d62 409
734689b1 410 mg = condpair_magic(sv);
683929b4 411 DEBUG_L(PerlIO_printf(PerlIO_stderr(), "%p: cond_signal %p\n",thr,sv));
734689b1
MB
412 MUTEX_LOCK(MgMUTEXP(mg));
413 if (MgOWNER(mg) != thr) {
414 MUTEX_UNLOCK(MgMUTEXP(mg));
415 croak("cond_signal for lock that we don't own\n");
416 }
417 COND_SIGNAL(MgCONDP(mg));
418 MUTEX_UNLOCK(MgMUTEXP(mg));
d9bb3666 419
734689b1
MB
420void
421cond_broadcast(sv)
422 SV * sv
423 MAGIC * mg = NO_INIT
424CODE:
783070da 425 if (SvROK(sv))
734689b1 426 sv = SvRV(sv);
783070da 427
734689b1 428 mg = condpair_magic(sv);
683929b4
MB
429 DEBUG_L(PerlIO_printf(PerlIO_stderr(), "%p: cond_broadcast %p\n",
430 thr, sv));
734689b1
MB
431 MUTEX_LOCK(MgMUTEXP(mg));
432 if (MgOWNER(mg) != thr) {
433 MUTEX_UNLOCK(MgMUTEXP(mg));
434 croak("cond_broadcast for lock that we don't own\n");
435 }
436 COND_BROADCAST(MgCONDP(mg));
437 MUTEX_UNLOCK(MgMUTEXP(mg));
f152979c 438
7d901afa
MB
439void
440list(class)
441 char * class
442 PREINIT:
443 Thread t;
444 AV * av;
445 SV ** svp;
446 int n = 0;
447 PPCODE:
448 av = newAV();
449 /*
450 * Iterate until we have enough dynamic storage for all threads.
451 * We mustn't do any allocation while holding threads_mutex though.
452 */
453 MUTEX_LOCK(&threads_mutex);
454 do {
455 n = nthreads;
456 MUTEX_UNLOCK(&threads_mutex);
457 if (AvFILL(av) < n - 1) {
458 int i = AvFILL(av);
459 for (i = AvFILL(av); i < n - 1; i++) {
460 SV *sv = newSViv(0); /* fill in tid later */
461 sv_magic(sv, 0, '~', 0, 0); /* fill in other magic later */
462 av_push(av, sv_bless(newRV_noinc(sv),
463 gv_stashpv(class, TRUE)));
50112d62 464
7d901afa
MB
465 }
466 }
467 MUTEX_LOCK(&threads_mutex);
468 } while (n < nthreads);
50112d62 469 n = nthreads; /* Get the final correct value */
7d901afa
MB
470
471 /*
472 * At this point, there's enough room to fill in av.
473 * Note that we are holding threads_mutex so the list
474 * won't change out from under us but all the remaining
475 * processing is "fast" (no blocking, malloc etc.)
476 */
477 t = thr;
478 svp = AvARRAY(av);
479 do {
0a00ffdb 480 SV *sv = (SV*)SvRV(*svp);
7d901afa
MB
481 sv_setiv(sv, t->tid);
482 SvMAGIC(sv)->mg_obj = SvREFCNT_inc(t->Toursv);
483 SvMAGIC(sv)->mg_flags |= MGf_REFCOUNTED;
484 SvMAGIC(sv)->mg_private = Thread_MAGIC_SIGNATURE;
485 t = t->next;
0a00ffdb 486 svp++;
7d901afa 487 } while (t != thr);
50112d62 488 /* */
7d901afa
MB
489 MUTEX_UNLOCK(&threads_mutex);
490 /* Truncate any unneeded slots in av */
50112d62 491 av_fill(av, n - 1);
7d901afa
MB
492 /* Finally, push all the new objects onto the stack and drop av */
493 EXTEND(sp, n);
494 for (svp = AvARRAY(av); n > 0; n--, svp++)
495 PUSHs(*svp);
496 (void)sv_2mortal((SV*)av);
497
498
f152979c
MB
499MODULE = Thread PACKAGE = Thread::Signal
500
501void
502kill_sighandler_thread()
503 PPCODE:
504 write(sig_pipe[0], "\0", 1);
505 PUSHs(&sv_yes);
506
507void
508init_thread_signals()
509 PPCODE:
510 sighandlerp = handle_thread_signal;
511 if (pipe(sig_pipe) == -1)
512 XSRETURN_UNDEF;
513 PUSHs(&sv_yes);
514
515SV *
516await_signal()
517 PREINIT:
518 char c;
ea0efc06 519 SSize_t ret;
f152979c
MB
520 CODE:
521 do {
522 ret = read(sig_pipe[1], &c, 1);
523 } while (ret == -1 && errno == EINTR);
524 if (ret == -1)
525 croak("panic: await_signal");
526 if (ret == 0)
527 XSRETURN_UNDEF;
528 RETVAL = c ? psig_ptr[c] : &sv_no;
529 OUTPUT:
530 RETVAL