This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Convert miniperl sources to ANSI C. Several passes of
[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
MB
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
MB
154 DEBUG_L(PerlIO_printf(PerlIO_stderr(),
155 "%p: threadstart finishing: state is %u\n",
156 thr, ThrSTATE(thr)));
14fcddff
MB
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
MB
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
MB
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
MB
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
MB
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
MB
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
MB
188}
189
683929b4
MB
190static SV *
191newthread(startsv, initargs, class)
d9bb3666
MB
192SV *startsv;
193AV *initargs;
683929b4 194char *class;
d9bb3666
MB
195{
196 dTHR;
197 dSP;
198 Thread savethread;
199 int i;
683929b4 200 SV *sv;
ea0efc06
MB
201 int err;
202#ifndef THREAD_CREATE
f152979c 203 sigset_t fullmask, oldmask;
ea0efc06 204#endif
d9bb3666
MB
205
206 savethread = thr;
683929b4
MB
207 sv = newSVpv("", 0);
208 SvGROW(sv, sizeof(struct thread) + 1);
209 SvCUR_set(sv, sizeof(struct thread));
210 thr = (Thread) SvPVX(sv);
50112d62 211 DEBUG_L(PerlIO_printf(PerlIO_stderr(), "%p: newthread(%s) = %p)\n",
7d901afa 212 savethread, SvPEEK(startsv), thr));
683929b4 213 oursv = sv;
783070da
MB
214 /* If we don't zero these foostack pointers, init_stacks won't init them */
215 markstack = 0;
216 scopestack = 0;
217 savestack = 0;
218 retstack = 0;
d9bb3666 219 init_stacks(ARGS);
783070da 220 curcop = savethread->Tcurcop; /* XXX As good a guess as any? */
d9bb3666
MB
221 SPAGAIN;
222 defstash = savethread->Tdefstash; /* XXX maybe these should */
223 curstash = savethread->Tcurstash; /* always be set to main? */
d9bb3666
MB
224 /* top_env? */
225 /* runlevel */
226 cvcache = newHV();
14fcddff
MB
227 thr->flags = THRf_R_JOINABLE;
228 MUTEX_INIT(&thr->mutex);
7d901afa
MB
229 thr->tid = ++threadnum;
230 /* Insert new thread into the circular linked list and bump nthreads */
231 MUTEX_LOCK(&threads_mutex);
232 thr->next = savethread->next;
233 thr->prev = savethread;
234 savethread->next = thr;
235 thr->next->prev = thr;
236 nthreads++;
237 MUTEX_UNLOCK(&threads_mutex);
d9bb3666 238
50112d62
MB
239 DEBUG_L(PerlIO_printf(PerlIO_stderr(),
240 "%p: newthread, tid is %u, preparing stack\n",
241 savethread, thr->tid));
d9bb3666
MB
242 /* The following pushes the arg list and startsv onto the *new* stack */
243 PUSHMARK(sp);
244 /* Could easily speed up the following greatly */
734689b1 245 for (i = 0; i <= AvFILL(initargs); i++)
d9bb3666
MB
246 XPUSHs(SvREFCNT_inc(*av_fetch(initargs, i, FALSE)));
247 XPUSHs(SvREFCNT_inc(startsv));
248 PUTBACK;
249
ea0efc06
MB
250#ifdef THREAD_CREATE
251 THREAD_CREATE(thr, threadstart);
783070da 252#else
d9bb3666 253 /* On your marks... */
14fcddff 254 MUTEX_LOCK(&thr->mutex);
ea0efc06 255 /* Get set... */
f152979c
MB
256 sigfillset(&fullmask);
257 if (sigprocmask(SIG_SETMASK, &fullmask, &oldmask) == -1)
258 croak("panic: sigprocmask");
46930d8f
MB
259 err = pthread_create(&thr->self, pthread_attr_default,
260 threadstart, (void*) thr);
d9bb3666 261 /* Go */
14fcddff 262 MUTEX_UNLOCK(&thr->mutex);
ea0efc06
MB
263#endif
264 if (err) {
265 /* Thread creation failed--clean up */
266 SvREFCNT_dec(cvcache);
267 remove_thread(thr);
268 MUTEX_DESTROY(&thr->mutex);
269 for (i = 0; i <= AvFILL(initargs); i++)
270 SvREFCNT_dec(*av_fetch(initargs, i, FALSE));
271 SvREFCNT_dec(startsv);
272 return NULL;
273 }
274#ifdef THREAD_POST_CREATE
275 THREAD_POST_CREATE(thr);
276#else
f152979c
MB
277 if (sigprocmask(SIG_SETMASK, &oldmask, 0))
278 croak("panic: sigprocmask");
783070da 279#endif
7d901afa 280 sv = newSViv(thr->tid);
683929b4 281 sv_magic(sv, oursv, '~', 0, 0);
7d901afa
MB
282 SvMAGIC(sv)->mg_private = Thread_MAGIC_SIGNATURE;
283 return sv_bless(newRV_noinc(sv), gv_stashpv(class, TRUE));
d9bb3666
MB
284}
285
f152979c
MB
286static Signal_t
287handle_thread_signal(sig)
288int sig;
289{
290 char c = (char) sig;
291 write(sig_pipe[0], &c, 1);
292}
293
d9bb3666
MB
294MODULE = Thread PACKAGE = Thread
295
683929b4 296void
d9bb3666 297new(class, startsv, ...)
683929b4 298 char * class
d9bb3666 299 SV * startsv
734689b1 300 AV * av = av_make(items - 2, &ST(2));
683929b4
MB
301 PPCODE:
302 XPUSHs(sv_2mortal(newthread(startsv, av, class)));
d9bb3666
MB
303
304void
d9bb3666
MB
305join(t)
306 Thread t
307 AV * av = NO_INIT
308 int i = NO_INIT
309 PPCODE:
7d901afa
MB
310 DEBUG_L(PerlIO_printf(PerlIO_stderr(), "%p: joining %p (state %u)\n",
311 thr, t, ThrSTATE(t)););
50112d62
MB
312 MUTEX_LOCK(&t->mutex);
313 switch (ThrSTATE(t)) {
14fcddff
MB
314 case THRf_R_JOINABLE:
315 case THRf_R_JOINED:
50112d62
MB
316 ThrSETSTATE(t, THRf_R_JOINED);
317 MUTEX_UNLOCK(&t->mutex);
14fcddff
MB
318 break;
319 case THRf_ZOMBIE:
50112d62
MB
320 ThrSETSTATE(t, THRf_DEAD);
321 MUTEX_UNLOCK(&t->mutex);
322 remove_thread(t);
14fcddff
MB
323 break;
324 default:
50112d62 325 MUTEX_UNLOCK(&t->mutex);
14fcddff
MB
326 croak("can't join with thread");
327 /* NOTREACHED */
328 }
ea0efc06 329 JOIN(t, &av);
7d901afa 330
d9bb3666
MB
331 /* Could easily speed up the following if necessary */
332 for (i = 0; i <= AvFILL(av); i++)
333 XPUSHs(sv_2mortal(*av_fetch(av, i, FALSE)));
334
335void
734689b1 336detach(t)
d9bb3666
MB
337 Thread t
338 CODE:
7d901afa
MB
339 DEBUG_L(PerlIO_printf(PerlIO_stderr(), "%p: detaching %p (state %u)\n",
340 thr, t, ThrSTATE(t)););
50112d62
MB
341 MUTEX_LOCK(&t->mutex);
342 switch (ThrSTATE(t)) {
14fcddff 343 case THRf_R_JOINABLE:
50112d62 344 ThrSETSTATE(t, THRf_R_DETACHED);
14fcddff 345 /* fall through */
50112d62 346 case THRf_R_DETACHED:
14fcddff 347 DETACH(t);
50112d62 348 MUTEX_UNLOCK(&t->mutex);
14fcddff
MB
349 break;
350 case THRf_ZOMBIE:
50112d62 351 ThrSETSTATE(t, THRf_DEAD);
7d901afa 352 DETACH(t);
50112d62
MB
353 MUTEX_UNLOCK(&t->mutex);
354 remove_thread(t);
14fcddff
MB
355 break;
356 default:
50112d62 357 MUTEX_UNLOCK(&t->mutex);
14fcddff
MB
358 croak("can't detach thread");
359 /* NOTREACHED */
734689b1 360 }
d9bb3666
MB
361
362void
7d901afa
MB
363equal(t1, t2)
364 Thread t1
365 Thread t2
366 PPCODE:
367 PUSHs((t1 == t2) ? &sv_yes : &sv_no);
368
369void
370flags(t)
371 Thread t
372 PPCODE:
373 PUSHs(sv_2mortal(newSViv(t->flags)));
374
375void
376self(class)
377 char * class
378 PREINIT:
379 SV *sv;
380 PPCODE:
381 sv = newSViv(thr->tid);
382 sv_magic(sv, oursv, '~', 0, 0);
383 SvMAGIC(sv)->mg_private = Thread_MAGIC_SIGNATURE;
384 PUSHs(sv_2mortal(sv_bless(newRV_noinc(sv), gv_stashpv(class, TRUE))));
385
50112d62
MB
386U32
387tid(t)
388 Thread t
389 CODE:
390 MUTEX_LOCK(&t->mutex);
391 RETVAL = t->tid;
392 MUTEX_UNLOCK(&t->mutex);
393 OUTPUT:
394 RETVAL
395
396void
397DESTROY(t)
398 SV * t
399 PPCODE:
400 PUSHs(&sv_yes);
401
7d901afa 402void
734689b1 403yield()
d9bb3666 404 CODE:
ea0efc06 405 YIELD;
d9bb3666
MB
406
407void
734689b1
MB
408cond_wait(sv)
409 SV * sv
410 MAGIC * mg = NO_INIT
411CODE:
2c127b02 412 if (SvROK(sv))
734689b1 413 sv = SvRV(sv);
2c127b02 414
734689b1 415 mg = condpair_magic(sv);
683929b4 416 DEBUG_L(PerlIO_printf(PerlIO_stderr(), "%p: cond_wait %p\n", thr, sv));
734689b1
MB
417 MUTEX_LOCK(MgMUTEXP(mg));
418 if (MgOWNER(mg) != thr) {
419 MUTEX_UNLOCK(MgMUTEXP(mg));
420 croak("cond_wait for lock that we don't own\n");
421 }
422 MgOWNER(mg) = 0;
423 COND_WAIT(MgCONDP(mg), MgMUTEXP(mg));
50112d62
MB
424 while (MgOWNER(mg))
425 COND_WAIT(MgOWNERCONDP(mg), MgMUTEXP(mg));
734689b1
MB
426 MgOWNER(mg) = thr;
427 MUTEX_UNLOCK(MgMUTEXP(mg));
428
429void
430cond_signal(sv)
431 SV * sv
432 MAGIC * mg = NO_INIT
433CODE:
50112d62 434 if (SvROK(sv))
734689b1 435 sv = SvRV(sv);
50112d62 436
734689b1 437 mg = condpair_magic(sv);
683929b4 438 DEBUG_L(PerlIO_printf(PerlIO_stderr(), "%p: cond_signal %p\n",thr,sv));
734689b1
MB
439 MUTEX_LOCK(MgMUTEXP(mg));
440 if (MgOWNER(mg) != thr) {
441 MUTEX_UNLOCK(MgMUTEXP(mg));
442 croak("cond_signal for lock that we don't own\n");
443 }
444 COND_SIGNAL(MgCONDP(mg));
445 MUTEX_UNLOCK(MgMUTEXP(mg));
d9bb3666 446
734689b1
MB
447void
448cond_broadcast(sv)
449 SV * sv
450 MAGIC * mg = NO_INIT
451CODE:
783070da 452 if (SvROK(sv))
734689b1 453 sv = SvRV(sv);
783070da 454
734689b1 455 mg = condpair_magic(sv);
683929b4
MB
456 DEBUG_L(PerlIO_printf(PerlIO_stderr(), "%p: cond_broadcast %p\n",
457 thr, sv));
734689b1
MB
458 MUTEX_LOCK(MgMUTEXP(mg));
459 if (MgOWNER(mg) != thr) {
460 MUTEX_UNLOCK(MgMUTEXP(mg));
461 croak("cond_broadcast for lock that we don't own\n");
462 }
463 COND_BROADCAST(MgCONDP(mg));
464 MUTEX_UNLOCK(MgMUTEXP(mg));
f152979c 465
7d901afa
MB
466void
467list(class)
468 char * class
469 PREINIT:
470 Thread t;
471 AV * av;
472 SV ** svp;
473 int n = 0;
474 PPCODE:
475 av = newAV();
476 /*
477 * Iterate until we have enough dynamic storage for all threads.
478 * We mustn't do any allocation while holding threads_mutex though.
479 */
480 MUTEX_LOCK(&threads_mutex);
481 do {
482 n = nthreads;
483 MUTEX_UNLOCK(&threads_mutex);
484 if (AvFILL(av) < n - 1) {
485 int i = AvFILL(av);
486 for (i = AvFILL(av); i < n - 1; i++) {
487 SV *sv = newSViv(0); /* fill in tid later */
488 sv_magic(sv, 0, '~', 0, 0); /* fill in other magic later */
489 av_push(av, sv_bless(newRV_noinc(sv),
490 gv_stashpv(class, TRUE)));
50112d62 491
7d901afa
MB
492 }
493 }
494 MUTEX_LOCK(&threads_mutex);
495 } while (n < nthreads);
50112d62 496 n = nthreads; /* Get the final correct value */
7d901afa
MB
497
498 /*
499 * At this point, there's enough room to fill in av.
500 * Note that we are holding threads_mutex so the list
501 * won't change out from under us but all the remaining
502 * processing is "fast" (no blocking, malloc etc.)
503 */
504 t = thr;
505 svp = AvARRAY(av);
506 do {
0a00ffdb 507 SV *sv = (SV*)SvRV(*svp);
7d901afa
MB
508 sv_setiv(sv, t->tid);
509 SvMAGIC(sv)->mg_obj = SvREFCNT_inc(t->Toursv);
510 SvMAGIC(sv)->mg_flags |= MGf_REFCOUNTED;
511 SvMAGIC(sv)->mg_private = Thread_MAGIC_SIGNATURE;
512 t = t->next;
0a00ffdb 513 svp++;
7d901afa 514 } while (t != thr);
50112d62 515 /* */
7d901afa
MB
516 MUTEX_UNLOCK(&threads_mutex);
517 /* Truncate any unneeded slots in av */
50112d62 518 av_fill(av, n - 1);
7d901afa
MB
519 /* Finally, push all the new objects onto the stack and drop av */
520 EXTEND(sp, n);
521 for (svp = AvARRAY(av); n > 0; n--, svp++)
522 PUSHs(*svp);
523 (void)sv_2mortal((SV*)av);
524
525
f152979c
MB
526MODULE = Thread PACKAGE = Thread::Signal
527
528void
529kill_sighandler_thread()
530 PPCODE:
531 write(sig_pipe[0], "\0", 1);
532 PUSHs(&sv_yes);
533
534void
535init_thread_signals()
536 PPCODE:
537 sighandlerp = handle_thread_signal;
538 if (pipe(sig_pipe) == -1)
539 XSRETURN_UNDEF;
540 PUSHs(&sv_yes);
541
542SV *
543await_signal()
544 PREINIT:
545 char c;
ea0efc06 546 SSize_t ret;
f152979c
MB
547 CODE:
548 do {
549 ret = read(sig_pipe[1], &c, 1);
550 } while (ret == -1 && errno == EINTR);
551 if (ret == -1)
552 croak("panic: await_signal");
553 if (ret == 0)
554 XSRETURN_UNDEF;
555 RETVAL = c ? psig_ptr[c] : &sv_no;
556 OUTPUT:
557 RETVAL