This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Started rewriting thread state machine.
[perl5.git] / 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);
18 nthreads--;
19 t->prev->next = t->next;
20 t->next->prev = t->prev;
21 COND_BROADCAST(&nthreads_cond);
22 MUTEX_UNLOCK(&threads_mutex);
23}
24
d9bb3666
MB
25static void *
26threadstart(arg)
27void *arg;
28{
783070da
MB
29#ifdef FAKE_THREADS
30 Thread savethread = thr;
31 LOGOP myop;
32 dSP;
33 I32 oldscope = scopestack_ix;
34 I32 retval;
35 AV *returnav = newAV();
36 int i;
37
683929b4
MB
38 DEBUG_L(PerlIO_printf(PerlIO_stderr(), "new thread %p starting at %s\n",
39 thr, SvPEEK(TOPs)));
783070da
MB
40 thr = (Thread) arg;
41 savemark = TOPMARK;
42 thr->prev = thr->prev_run = savethread;
43 thr->next = savethread->next;
44 thr->next_run = savethread->next_run;
45 savethread->next = savethread->next_run = thr;
46 thr->wait_queue = 0;
47 thr->private = 0;
48
49 /* Now duplicate most of perl_call_sv but with a few twists */
50 op = (OP*)&myop;
51 Zero(op, 1, LOGOP);
52 myop.op_flags = OPf_STACKED;
53 myop.op_next = Nullop;
54 myop.op_flags |= OPf_KNOW;
55 myop.op_flags |= OPf_WANT_LIST;
56 op = pp_entersub(ARGS);
57 DEBUG_L(if (!op)
58 PerlIO_printf(PerlIO_stderr(), "thread starts at Nullop\n"));
59 /*
60 * When this thread is next scheduled, we start in the right
61 * place. When the thread runs off the end of the sub, perl.c
62 * handles things, using savemark to figure out how much of the
63 * stack is the return value for any join.
64 */
65 thr = savethread; /* back to the old thread */
66 return 0;
67#else
d9bb3666
MB
68 Thread thr = (Thread) arg;
69 LOGOP myop;
70 dSP;
71 I32 oldmark = TOPMARK;
72 I32 oldscope = scopestack_ix;
73 I32 retval;
74 AV *returnav = newAV();
14fcddff 75 int i, ret;
783070da 76 dJMPENV;
783070da
MB
77
78 /* Don't call *anything* requiring dTHR until after pthread_setspecific */
d9bb3666
MB
79 /*
80 * Wait until our creator releases us. If we didn't do this, then
81 * it would be potentially possible for out thread to carry on and
82 * do stuff before our creator fills in our "self" field. For example,
83 * if we went and created another thread which tried to pthread_join
84 * with us, then we'd be in a mess.
85 */
14fcddff
MB
86 MUTEX_LOCK(thr->mutex);
87 MUTEX_UNLOCK(thr->mutex);
d9bb3666 88
d9bb3666
MB
89 /*
90 * It's safe to wait until now to set the thread-specific pointer
91 * from our pthread_t structure to our struct thread, since we're
92 * the only thread who can get at it anyway.
93 */
94 if (pthread_setspecific(thr_key, (void *) thr))
95 croak("panic: pthread_setspecific");
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]));)
d9bb3666 135 av_store(returnav, 0, newSVpv("", 0));
734689b1
MB
136 for (i = 1; i <= retval; i++, sp++)
137 sv_setsv(*av_fetch(returnav, i, TRUE), SvREFCNT_inc(*sp));
138
d9bb3666 139 finishoff:
783070da
MB
140#if 0
141 /* removed for debug */
142 SvREFCNT_dec(curstack);
143#endif
d9bb3666
MB
144 SvREFCNT_dec(cvcache);
145 Safefree(markstack);
146 Safefree(scopestack);
147 Safefree(savestack);
148 Safefree(retstack);
149 Safefree(cxstack);
150 Safefree(tmps_stack);
151
14fcddff
MB
152 MUTEX_LOCK(&thr->mutex);
153 switch (ThrSTATE(thr)) {
154 case THRf_R_JOINABLE:
155 ThrSETSTATE(thr, THRf_ZOMBIE);
156 MUTEX_UNLOCK(&thr->mutex);
783070da 157 DEBUG_L(PerlIO_printf(PerlIO_stderr(),
14fcddff
MB
158 "%p: R_JOINABLE thread finished\n", thr));
159 break;
160 case THRf_R_JOINED:
161 ThrSETSTATE(thr, THRf_DEAD);
162 MUTEX_UNLOCK(&thr->mutex);
163 DEBUG_L(PerlIO_printf(PerlIO_stderr(),
164 "%p: R_JOINED thread finished\n", thr));
165 break;
166 case THRf_DETACHED:
683929b4 167 ThrSETSTATE(thr, THRf_DEAD);
14fcddff 168 MUTEX_UNLOCK(&thr->mutex);
7d901afa 169 remove_thread(thr);
14fcddff
MB
170 SvREFCNT_dec(returnav);
171 DEBUG_L(PerlIO_printf(PerlIO_stderr(),
172 "%p: DETACHED thread finished\n", thr));
173 break;
174 default:
175 MUTEX_UNLOCK(&thr->mutex);
176 croak("panic: illegal state %u at end of threadstart", ThrSTATE(thr));
177 /* NOTREACHED */
734689b1 178 }
14fcddff 179 MUTEX_DESTROY(&thr->mutex);
783070da 180 DEBUG_L(PerlIO_printf(PerlIO_stderr(), "%p returning\n", thr));
d9bb3666 181 return (void *) returnav; /* Available for anyone to join with us */
734689b1
MB
182 /* unless we are detached in which case */
183 /* noone will see the value anyway. */
783070da 184#endif
d9bb3666
MB
185}
186
683929b4
MB
187static SV *
188newthread(startsv, initargs, class)
d9bb3666
MB
189SV *startsv;
190AV *initargs;
683929b4 191char *class;
d9bb3666
MB
192{
193 dTHR;
194 dSP;
195 Thread savethread;
196 int i;
683929b4 197 SV *sv;
f152979c 198 sigset_t fullmask, oldmask;
d9bb3666
MB
199
200 savethread = thr;
683929b4
MB
201 sv = newSVpv("", 0);
202 SvGROW(sv, sizeof(struct thread) + 1);
203 SvCUR_set(sv, sizeof(struct thread));
204 thr = (Thread) SvPVX(sv);
7d901afa
MB
205 DEBUG_L(PerlIO_printf(PerlIO_stderr(), "%p: newthread(%s) = %p\n",
206 savethread, SvPEEK(startsv), thr));
683929b4 207 oursv = sv;
783070da
MB
208 /* If we don't zero these foostack pointers, init_stacks won't init them */
209 markstack = 0;
210 scopestack = 0;
211 savestack = 0;
212 retstack = 0;
d9bb3666 213 init_stacks(ARGS);
783070da 214 curcop = savethread->Tcurcop; /* XXX As good a guess as any? */
d9bb3666
MB
215 SPAGAIN;
216 defstash = savethread->Tdefstash; /* XXX maybe these should */
217 curstash = savethread->Tcurstash; /* always be set to main? */
d9bb3666
MB
218 /* top_env? */
219 /* runlevel */
220 cvcache = newHV();
14fcddff
MB
221 thr->flags = THRf_R_JOINABLE;
222 MUTEX_INIT(&thr->mutex);
7d901afa
MB
223 thr->tid = ++threadnum;
224 /* Insert new thread into the circular linked list and bump nthreads */
225 MUTEX_LOCK(&threads_mutex);
226 thr->next = savethread->next;
227 thr->prev = savethread;
228 savethread->next = thr;
229 thr->next->prev = thr;
230 nthreads++;
231 MUTEX_UNLOCK(&threads_mutex);
d9bb3666 232
7d901afa
MB
233 DEBUG_L(PerlIO_printf(PerlIO_stderr(), "%p: newthread preparing stack\n",
234 savethread));
d9bb3666
MB
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
MB
239 XPUSHs(SvREFCNT_inc(*av_fetch(initargs, i, FALSE)));
240 XPUSHs(SvREFCNT_inc(startsv));
241 PUTBACK;
242
783070da
MB
243#ifdef FAKE_THREADS
244 threadstart(thr);
245#else
d9bb3666 246 /* On your marks... */
14fcddff 247 MUTEX_LOCK(&thr->mutex);
d9bb3666
MB
248 /* Get set...
249 * Increment the global thread count. It is decremented
250 * by the destructor for the thread specific key thr_key.
251 */
f152979c
MB
252 sigfillset(&fullmask);
253 if (sigprocmask(SIG_SETMASK, &fullmask, &oldmask) == -1)
254 croak("panic: sigprocmask");
d9bb3666
MB
255 if (pthread_create(&self, NULL, threadstart, (void*) thr))
256 return NULL; /* XXX should clean up first */
257 /* Go */
14fcddff 258 MUTEX_UNLOCK(&thr->mutex);
f152979c
MB
259 if (sigprocmask(SIG_SETMASK, &oldmask, 0))
260 croak("panic: sigprocmask");
783070da 261#endif
7d901afa 262 sv = newSViv(thr->tid);
683929b4 263 sv_magic(sv, oursv, '~', 0, 0);
7d901afa
MB
264 SvMAGIC(sv)->mg_private = Thread_MAGIC_SIGNATURE;
265 return sv_bless(newRV_noinc(sv), gv_stashpv(class, TRUE));
d9bb3666
MB
266}
267
f152979c
MB
268static Signal_t
269handle_thread_signal(sig)
270int sig;
271{
272 char c = (char) sig;
273 write(sig_pipe[0], &c, 1);
274}
275
d9bb3666
MB
276MODULE = Thread PACKAGE = Thread
277
683929b4 278void
d9bb3666 279new(class, startsv, ...)
683929b4 280 char * class
d9bb3666 281 SV * startsv
734689b1 282 AV * av = av_make(items - 2, &ST(2));
683929b4
MB
283 PPCODE:
284 XPUSHs(sv_2mortal(newthread(startsv, av, class)));
d9bb3666
MB
285
286void
d9bb3666
MB
287join(t)
288 Thread t
289 AV * av = NO_INIT
290 int i = NO_INIT
291 PPCODE:
7d901afa
MB
292 DEBUG_L(PerlIO_printf(PerlIO_stderr(), "%p: joining %p (state %u)\n",
293 thr, t, ThrSTATE(t)););
14fcddff
MB
294 MUTEX_LOCK(&thr->mutex);
295 switch (ThrSTATE(thr)) {
296 case THRf_R_JOINABLE:
297 case THRf_R_JOINED:
298 ThrSETSTATE(thr, THRf_R_JOINED);
299 MUTEX_UNLOCK(&thr->mutex);
300 break;
301 case THRf_ZOMBIE:
302 ThrSETSTATE(thr, THRf_DEAD);
303 MUTEX_UNLOCK(&thr->mutex);
304 remove_thread(thr);
305 break;
306 default:
307 MUTEX_UNLOCK(&thr->mutex);
308 croak("can't join with thread");
309 /* NOTREACHED */
310 }
d9bb3666
MB
311 if (pthread_join(t->Tself, (void **) &av))
312 croak("pthread_join failed");
7d901afa 313
d9bb3666
MB
314 /* Could easily speed up the following if necessary */
315 for (i = 0; i <= AvFILL(av); i++)
316 XPUSHs(sv_2mortal(*av_fetch(av, i, FALSE)));
317
318void
734689b1 319detach(t)
d9bb3666
MB
320 Thread t
321 CODE:
7d901afa
MB
322 DEBUG_L(PerlIO_printf(PerlIO_stderr(), "%p: detaching %p (state %u)\n",
323 thr, t, ThrSTATE(t)););
14fcddff
MB
324 switch (ThrSTATE(thr)) {
325 case THRf_R_JOINABLE:
326 ThrSETSTATE(thr, THRf_DETACHED);
327 /* fall through */
328 case THRf_DETACHED:
329 MUTEX_UNLOCK(&thr->mutex);
330 DETACH(t);
331 break;
332 case THRf_ZOMBIE:
333 ThrSETSTATE(thr, THRf_DEAD);
334 MUTEX_UNLOCK(&thr->mutex);
335 remove_thread(thr);
7d901afa 336 DETACH(t);
14fcddff
MB
337 break;
338 default:
339 MUTEX_UNLOCK(&thr->mutex);
340 croak("can't detach thread");
341 /* NOTREACHED */
734689b1 342 }
d9bb3666
MB
343
344void
7d901afa
MB
345equal(t1, t2)
346 Thread t1
347 Thread t2
348 PPCODE:
349 PUSHs((t1 == t2) ? &sv_yes : &sv_no);
350
351void
352flags(t)
353 Thread t
354 PPCODE:
355 PUSHs(sv_2mortal(newSViv(t->flags)));
356
357void
358self(class)
359 char * class
360 PREINIT:
361 SV *sv;
362 PPCODE:
363 sv = newSViv(thr->tid);
364 sv_magic(sv, oursv, '~', 0, 0);
365 SvMAGIC(sv)->mg_private = Thread_MAGIC_SIGNATURE;
366 PUSHs(sv_2mortal(sv_bless(newRV_noinc(sv), gv_stashpv(class, TRUE))));
367
368void
734689b1 369yield()
d9bb3666 370 CODE:
734689b1
MB
371#ifdef OLD_PTHREADS_API
372 pthread_yield();
373#else
374#ifndef NO_SCHED_YIELD
375 sched_yield();
376#endif /* NO_SCHED_YIELD */
377#endif /* OLD_PTHREADS_API */
d9bb3666
MB
378
379void
734689b1
MB
380cond_wait(sv)
381 SV * sv
382 MAGIC * mg = NO_INIT
383CODE:
2c127b02 384 if (SvROK(sv))
734689b1 385 sv = SvRV(sv);
2c127b02 386
734689b1 387 mg = condpair_magic(sv);
683929b4 388 DEBUG_L(PerlIO_printf(PerlIO_stderr(), "%p: cond_wait %p\n", thr, sv));
734689b1
MB
389 MUTEX_LOCK(MgMUTEXP(mg));
390 if (MgOWNER(mg) != thr) {
391 MUTEX_UNLOCK(MgMUTEXP(mg));
392 croak("cond_wait for lock that we don't own\n");
393 }
394 MgOWNER(mg) = 0;
395 COND_WAIT(MgCONDP(mg), MgMUTEXP(mg));
396 MgOWNER(mg) = thr;
397 MUTEX_UNLOCK(MgMUTEXP(mg));
398
399void
400cond_signal(sv)
401 SV * sv
402 MAGIC * mg = NO_INIT
403CODE:
404 if (SvROK(sv)) {
405 /*
406 * Kludge to allow lock of real objects without requiring
407 * to pass in every type of argument by explicit reference.
408 */
409 sv = SvRV(sv);
410 }
411 mg = condpair_magic(sv);
683929b4 412 DEBUG_L(PerlIO_printf(PerlIO_stderr(), "%p: cond_signal %p\n",thr,sv));
734689b1
MB
413 MUTEX_LOCK(MgMUTEXP(mg));
414 if (MgOWNER(mg) != thr) {
415 MUTEX_UNLOCK(MgMUTEXP(mg));
416 croak("cond_signal for lock that we don't own\n");
417 }
418 COND_SIGNAL(MgCONDP(mg));
419 MUTEX_UNLOCK(MgMUTEXP(mg));
d9bb3666 420
734689b1
MB
421void
422cond_broadcast(sv)
423 SV * sv
424 MAGIC * mg = NO_INIT
425CODE:
783070da 426 if (SvROK(sv))
734689b1 427 sv = SvRV(sv);
783070da 428
734689b1 429 mg = condpair_magic(sv);
683929b4
MB
430 DEBUG_L(PerlIO_printf(PerlIO_stderr(), "%p: cond_broadcast %p\n",
431 thr, sv));
734689b1
MB
432 MUTEX_LOCK(MgMUTEXP(mg));
433 if (MgOWNER(mg) != thr) {
434 MUTEX_UNLOCK(MgMUTEXP(mg));
435 croak("cond_broadcast for lock that we don't own\n");
436 }
437 COND_BROADCAST(MgCONDP(mg));
438 MUTEX_UNLOCK(MgMUTEXP(mg));
f152979c 439
7d901afa
MB
440void
441list(class)
442 char * class
443 PREINIT:
444 Thread t;
445 AV * av;
446 SV ** svp;
447 int n = 0;
448 PPCODE:
449 av = newAV();
450 /*
451 * Iterate until we have enough dynamic storage for all threads.
452 * We mustn't do any allocation while holding threads_mutex though.
453 */
454 MUTEX_LOCK(&threads_mutex);
455 do {
456 n = nthreads;
457 MUTEX_UNLOCK(&threads_mutex);
458 if (AvFILL(av) < n - 1) {
459 int i = AvFILL(av);
460 for (i = AvFILL(av); i < n - 1; i++) {
461 SV *sv = newSViv(0); /* fill in tid later */
462 sv_magic(sv, 0, '~', 0, 0); /* fill in other magic later */
463 av_push(av, sv_bless(newRV_noinc(sv),
464 gv_stashpv(class, TRUE)));
465 }
466 }
467 MUTEX_LOCK(&threads_mutex);
468 } while (n < nthreads);
469
470 /*
471 * At this point, there's enough room to fill in av.
472 * Note that we are holding threads_mutex so the list
473 * won't change out from under us but all the remaining
474 * processing is "fast" (no blocking, malloc etc.)
475 */
476 t = thr;
477 svp = AvARRAY(av);
478 do {
479 SV *sv = SvRV(*svp++);
480 sv_setiv(sv, t->tid);
481 SvMAGIC(sv)->mg_obj = SvREFCNT_inc(t->Toursv);
482 SvMAGIC(sv)->mg_flags |= MGf_REFCOUNTED;
483 SvMAGIC(sv)->mg_private = Thread_MAGIC_SIGNATURE;
484 t = t->next;
485 } while (t != thr);
486 /* Record the overflow */
487 n -= nthreads;
488 MUTEX_UNLOCK(&threads_mutex);
489 /* Truncate any unneeded slots in av */
490 if (n > 0)
491 av_fill(av, AvFILL(av) - n);
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;
519 ssize_t ret;
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