threads 1.57
[p5sagit/p5-mst-13.2.git] / ext / threads / threads.xs
CommitLineData
68795e93 1#define PERL_NO_GET_CONTEXT
2#include "EXTERN.h"
3#include "perl.h"
4#include "XSUB.h"
4dcb9e53 5/* Workaround for XSUB.h bug under WIN32 */
6#ifdef WIN32
7# undef setjmp
c608f8c0 8# if !defined(__BORLANDC__)
9# define setjmp(x) _setjmp(x)
10# endif
4dcb9e53 11#endif
0f1612a7 12#ifdef HAS_PPPORT_H
404aaa48 13# define NEED_PL_signals
0f1612a7 14# define NEED_newRV_noinc
15# define NEED_sv_2pv_nolen
16# include "ppport.h"
17# include "threads.h"
18#endif
68795e93 19
73e09c8f 20#ifdef USE_ITHREADS
21
68795e93 22#ifdef WIN32
fc04eb16 23# include <windows.h>
514612b7 24 /* Supposed to be in Winbase.h */
25# ifndef STACK_SIZE_PARAM_IS_A_RESERVATION
26# define STACK_SIZE_PARAM_IS_A_RESERVATION 0x00010000
27# endif
fc04eb16 28# include <win32thread.h>
68795e93 29#else
fc04eb16 30# ifdef OS2
5c728af0 31typedef perl_os_thread pthread_t;
fc04eb16 32# else
33# include <pthread.h>
34# endif
35# include <thread.h>
36# define PERL_THREAD_SETSPECIFIC(k,v) pthread_setspecific(k,v)
37# ifdef OLD_PTHREADS_API
38# define PERL_THREAD_DETACH(t) pthread_detach(&(t))
39# else
40# define PERL_THREAD_DETACH(t) pthread_detach((t))
41# endif
467f3f08 42#endif
d305c2c9 43#if !defined(HAS_GETPAGESIZE) && defined(I_SYS_PARAM)
44# include <sys/param.h>
45#endif
68795e93 46
62375a60 47/* Values for 'state' member */
69a9b4b8 48#define PERL_ITHR_DETACHED 1
49#define PERL_ITHR_JOINED 2
8718f9a1 50#define PERL_ITHR_UNCALLABLE (PERL_ITHR_DETACHED|PERL_ITHR_JOINED)
69a9b4b8 51#define PERL_ITHR_FINISHED 4
52#define PERL_ITHR_THREAD_EXIT_ONLY 8
adc09a0e 53#define PERL_ITHR_NONVIABLE 16
54#define PERL_ITHR_DESTROYED 32
955c272e 55#define PERL_ITHR_DIED 64
fc04eb16 56
57typedef struct _ithread {
58 struct _ithread *next; /* Next thread in the list */
59 struct _ithread *prev; /* Prev thread in the list */
60 PerlInterpreter *interp; /* The threads interpreter */
61 UV tid; /* Threads module's thread id */
62 perl_mutex mutex; /* Mutex for updating things in this struct */
9feacc09 63 int count; /* How many SVs have a reference to us */
fc04eb16 64 int state; /* Detached, joined, finished, etc. */
65 int gimme; /* Context of create */
66 SV *init_function; /* Code to run */
67 SV *params; /* Args to pass function */
68795e93 68#ifdef WIN32
fc04eb16 69 DWORD thr; /* OS's idea if thread id */
70 HANDLE handle; /* OS's waitable handle */
68795e93 71#else
fc04eb16 72 pthread_t thr; /* OS's handle for the thread */
68795e93 73#endif
514612b7 74 IV stack_size;
955c272e 75 SV *err; /* Error from abnormally terminated thread */
76 char *err_class; /* Error object's classname if applicable */
68795e93 77} ithread;
78
fc04eb16 79
5c6ff896 80#define MY_CXT_KEY "threads::_cxt" XS_VERSION
628ab322 81
82typedef struct {
861d5cbe 83 /* Used by Perl interpreter for thread context switching */
84 ithread *context;
628ab322 85} my_cxt_t;
86
87START_MY_CXT
88
68795e93 89
5c6ff896 90#define MY_POOL_KEY "threads::_pool" XS_VERSION
68795e93 91
5c6ff896 92typedef struct {
93 /* Structure for 'main' thread
94 * Also forms the 'base' for the doubly-linked list of threads */
95 ithread main_thread;
96
97 /* Protects the creation and destruction of threads*/
98 perl_mutex create_destruct_mutex;
99
100 UV tid_counter;
101 IV joinable_threads;
102 IV running_threads;
103 IV detached_threads;
104 IV default_stack_size;
105 IV page_size;
106} my_pool_t;
107
108#define dMY_POOL \
109 SV *my_pool_sv = *hv_fetch(PL_modglobal, MY_POOL_KEY, \
110 sizeof(MY_POOL_KEY)-1, TRUE); \
111 my_pool_t *my_poolp = INT2PTR(my_pool_t*, SvUV(my_pool_sv))
112
113#define MY_POOL (*my_poolp)
c05ae023 114
115
fc04eb16 116/* Used by Perl interpreter for thread context switching */
861d5cbe 117STATIC void
fc04eb16 118S_ithread_set(pTHX_ ithread *thread)
c05ae023 119{
628ab322 120 dMY_CXT;
861d5cbe 121 MY_CXT.context = thread;
c05ae023 122}
123
861d5cbe 124STATIC ithread *
fc04eb16 125S_ithread_get(pTHX)
126{
628ab322 127 dMY_CXT;
861d5cbe 128 return (MY_CXT.context);
c05ae023 129}
130
131
fc04eb16 132/* Free any data (such as the Perl interpreter) attached to an ithread
133 * structure. This is a bit like undef on SVs, where the SV isn't freed,
134 * but the PVX is. Must be called with thread->mutex already held.
2e676467 135 */
861d5cbe 136STATIC void
fc04eb16 137S_ithread_clear(pTHX_ ithread *thread)
2e676467 138{
139 PerlInterpreter *interp;
fc04eb16 140
adc09a0e 141 assert(((thread->state & PERL_ITHR_FINISHED) &&
8718f9a1 142 (thread->state & PERL_ITHR_UNCALLABLE))
adc09a0e 143 ||
144 (thread->state & PERL_ITHR_NONVIABLE));
2e676467 145
146 interp = thread->interp;
147 if (interp) {
fc04eb16 148 dTHXa(interp);
149
150 PERL_SET_CONTEXT(interp);
151 S_ithread_set(aTHX_ thread);
f2cba68d 152
fc04eb16 153 SvREFCNT_dec(thread->params);
154 thread->params = Nullsv;
2e676467 155
955c272e 156 if (thread->err) {
157 SvREFCNT_dec(thread->err);
158 thread->err = Nullsv;
159 }
160
fc04eb16 161 perl_destruct(interp);
9ca4d7fd 162 perl_free(interp);
fc04eb16 163 thread->interp = NULL;
2e676467 164 }
fc04eb16 165
2e676467 166 PERL_SET_CONTEXT(aTHX);
167}
168
68795e93 169
fc04eb16 170/* Free an ithread structure and any attached data if its count == 0 */
861d5cbe 171STATIC void
fc04eb16 172S_ithread_destruct(pTHX_ ithread *thread)
68795e93 173{
adc09a0e 174 int destroy = 0;
385d56e4 175#ifdef WIN32
fc04eb16 176 HANDLE handle;
385d56e4 177#endif
adc09a0e 178 dMY_POOL;
179
180 /* Determine if thread can be destroyed now */
181 MUTEX_LOCK(&thread->mutex);
fc04eb16 182 if (thread->count != 0) {
adc09a0e 183 destroy = 0;
184 } else if (thread->state & PERL_ITHR_DESTROYED) {
185 destroy = 0;
186 } else if (thread->state & PERL_ITHR_NONVIABLE) {
187 thread->state |= PERL_ITHR_DESTROYED;
188 destroy = 1;
189 } else if (! (thread->state & PERL_ITHR_FINISHED)) {
190 destroy = 0;
8718f9a1 191 } else if (! (thread->state & PERL_ITHR_UNCALLABLE)) {
adc09a0e 192 destroy = 0;
193 } else {
194 thread->state |= PERL_ITHR_DESTROYED;
195 destroy = 1;
fc04eb16 196 }
adc09a0e 197 MUTEX_UNLOCK(&thread->mutex);
198 if (! destroy) return;
9feacc09 199
fc04eb16 200 /* Main thread (0) is immortal and should never get here */
201 assert(thread->tid != 0);
202
203 /* Remove from circular list of threads */
5c6ff896 204 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
adc09a0e 205 assert(thread->prev && thread->next);
206 thread->next->prev = thread->prev;
207 thread->prev->next = thread->next;
fc04eb16 208 thread->next = NULL;
209 thread->prev = NULL;
5c6ff896 210 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
c2f2a82b 211
fc04eb16 212 /* Thread is now disowned */
9ca4d7fd 213 MUTEX_LOCK(&thread->mutex);
fc04eb16 214 S_ithread_clear(aTHX_ thread);
385d56e4 215
216#ifdef WIN32
fc04eb16 217 handle = thread->handle;
218 thread->handle = NULL;
385d56e4 219#endif
fc04eb16 220 MUTEX_UNLOCK(&thread->mutex);
221 MUTEX_DESTROY(&thread->mutex);
385d56e4 222
c7667023 223#ifdef WIN32
fea7688c 224 if (handle) {
fc04eb16 225 CloseHandle(handle);
fea7688c 226 }
c7667023 227#endif
385d56e4 228
fc04eb16 229 /* Call PerlMemShared_free() in the context of the "first" interpreter
230 * per http://www.nntp.perl.org/group/perl.perl5.porters/110772
231 */
5c6ff896 232 aTHX = MY_POOL.main_thread.interp;
fc04eb16 233 PerlMemShared_free(thread);
68795e93 234}
235
fc04eb16 236
69a9b4b8 237/* Warn if exiting with any unjoined threads */
861d5cbe 238STATIC int
69a9b4b8 239S_exit_warning(pTHX)
62375a60 240{
60bd5ef6 241 int veto_cleanup;
adc09a0e 242 dMY_POOL;
69a9b4b8 243
5c6ff896 244 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
245 veto_cleanup = (MY_POOL.running_threads || MY_POOL.joinable_threads);
246 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
60bd5ef6 247
248 if (veto_cleanup) {
fc04eb16 249 if (ckWARN_d(WARN_THREADS)) {
4dcb9e53 250 Perl_warn(aTHX_ "Perl exited with active threads:\n\t%"
251 IVdf " running and unjoined\n\t%"
252 IVdf " finished and unjoined\n\t%"
253 IVdf " running and detached\n",
5c6ff896 254 MY_POOL.running_threads,
255 MY_POOL.joinable_threads,
256 MY_POOL.detached_threads);
fc04eb16 257 }
62375a60 258 }
69a9b4b8 259
fc04eb16 260 return (veto_cleanup);
62375a60 261}
262
69a9b4b8 263/* Called on exit from main thread */
264int
265Perl_ithread_hook(pTHX)
266{
5c6ff896 267 dMY_POOL;
b5c80a23 268 return ((aTHX == MY_POOL.main_thread.interp) ? S_exit_warning(aTHX) : 0);
69a9b4b8 269}
270
68795e93 271
272/* MAGIC (in mg.h sense) hooks */
273
274int
275ithread_mg_get(pTHX_ SV *sv, MAGIC *mg)
276{
fc04eb16 277 ithread *thread = (ithread *)mg->mg_ptr;
45977657 278 SvIV_set(sv, PTR2IV(thread));
68795e93 279 SvIOK_on(sv);
fc04eb16 280 return (0);
68795e93 281}
282
283int
284ithread_mg_free(pTHX_ SV *sv, MAGIC *mg)
285{
f2cba68d 286 ithread *thread = (ithread *)mg->mg_ptr;
f2cba68d 287
68795e93 288 MUTEX_LOCK(&thread->mutex);
adc09a0e 289 thread->count--;
f2cba68d 290 MUTEX_UNLOCK(&thread->mutex);
291
adc09a0e 292 /* Try to clean up thread */
293 S_ithread_destruct(aTHX_ thread);
294
fc04eb16 295 return (0);
68795e93 296}
297
298int
299ithread_mg_dup(pTHX_ MAGIC *mg, CLONE_PARAMS *param)
300{
fc04eb16 301 ithread *thread = (ithread *)mg->mg_ptr;
68795e93 302 MUTEX_LOCK(&thread->mutex);
68795e93 303 thread->count++;
304 MUTEX_UNLOCK(&thread->mutex);
fc04eb16 305 return (0);
68795e93 306}
307
308MGVTBL ithread_vtbl = {
fc04eb16 309 ithread_mg_get, /* get */
310 0, /* set */
311 0, /* len */
312 0, /* clear */
313 ithread_mg_free, /* free */
314 0, /* copy */
315 ithread_mg_dup /* dup */
68795e93 316};
317
47ba8780 318
514612b7 319/* Provided default, minimum and rational stack sizes */
861d5cbe 320STATIC IV
321S_good_stack_size(pTHX_ IV stack_size)
514612b7 322{
5c6ff896 323 dMY_POOL;
324
514612b7 325 /* Use default stack size if no stack size specified */
fea7688c 326 if (! stack_size) {
5c6ff896 327 return (MY_POOL.default_stack_size);
fea7688c 328 }
514612b7 329
330#ifdef PTHREAD_STACK_MIN
331 /* Can't use less than minimum */
332 if (stack_size < PTHREAD_STACK_MIN) {
4dcb9e53 333 if (ckWARN(WARN_THREADS)) {
514612b7 334 Perl_warn(aTHX_ "Using minimum thread stack size of %" IVdf, (IV)PTHREAD_STACK_MIN);
335 }
336 return (PTHREAD_STACK_MIN);
337 }
338#endif
339
340 /* Round up to page size boundary */
5c6ff896 341 if (MY_POOL.page_size <= 0) {
d305c2c9 342#if defined(HAS_SYSCONF) && (defined(_SC_PAGESIZE) || defined(_SC_MMAP_PAGE_SIZE))
514612b7 343 SETERRNO(0, SS_NORMAL);
d305c2c9 344# ifdef _SC_PAGESIZE
5c6ff896 345 MY_POOL.page_size = sysconf(_SC_PAGESIZE);
d305c2c9 346# else
5c6ff896 347 MY_POOL.page_size = sysconf(_SC_MMAP_PAGE_SIZE);
d305c2c9 348# endif
5c6ff896 349 if ((long)MY_POOL.page_size < 0) {
514612b7 350 if (errno) {
351 SV * const error = get_sv("@", FALSE);
352 (void)SvUPGRADE(error, SVt_PV);
353 Perl_croak(aTHX_ "PANIC: sysconf: %s", SvPV_nolen(error));
354 } else {
355 Perl_croak(aTHX_ "PANIC: sysconf: pagesize unknown");
356 }
357 }
d305c2c9 358#else
359# ifdef HAS_GETPAGESIZE
5c6ff896 360 MY_POOL.page_size = getpagesize();
514612b7 361# else
d305c2c9 362# if defined(I_SYS_PARAM) && defined(PAGESIZE)
5c6ff896 363 MY_POOL.page_size = PAGESIZE;
d305c2c9 364# else
5c6ff896 365 MY_POOL.page_size = 8192; /* A conservative default */
d305c2c9 366# endif
514612b7 367# endif
5c6ff896 368 if (MY_POOL.page_size <= 0) {
369 Perl_croak(aTHX_ "PANIC: bad pagesize %" IVdf, (IV)MY_POOL.page_size);
fea7688c 370 }
514612b7 371#endif
372 }
5c6ff896 373 stack_size = ((stack_size + (MY_POOL.page_size - 1)) / MY_POOL.page_size) * MY_POOL.page_size;
514612b7 374
375 return (stack_size);
376}
377
378
fc04eb16 379/* Starts executing the thread.
380 * Passed as the C level function to run in the new thread.
b1edfb69 381 */
47ba8780 382#ifdef WIN32
861d5cbe 383STATIC THREAD_RET_TYPE
fc04eb16 384S_ithread_run(LPVOID arg)
47ba8780 385#else
861d5cbe 386STATIC void *
fc04eb16 387S_ithread_run(void * arg)
47ba8780 388#endif
fc04eb16 389{
390 ithread *thread = (ithread *)arg;
69a9b4b8 391 int jmp_rc = 0;
392 I32 oldscope;
955c272e 393 int exit_app = 0; /* Thread terminated using 'exit' */
69a9b4b8 394 int exit_code = 0;
955c272e 395 int died = 0; /* Thread terminated abnormally */
f2cba68d 396
69a9b4b8 397 dJMPENV;
398
fc04eb16 399 dTHXa(thread->interp);
47ba8780 400
5c6ff896 401 dMY_POOL;
402
9ca4d7fd 403 /* Blocked until ->create() call finishes */
fc04eb16 404 MUTEX_LOCK(&thread->mutex);
fc04eb16 405 MUTEX_UNLOCK(&thread->mutex);
9ca4d7fd 406
407 PERL_SET_CONTEXT(thread->interp);
408 S_ithread_set(aTHX_ thread);
47ba8780 409
fc04eb16 410 PL_perl_destruct_level = 2;
f2cba68d 411
fc04eb16 412 {
413 AV *params = (AV *)SvRV(thread->params);
414 int len = (int)av_len(params)+1;
415 int ii;
416
417 dSP;
418 ENTER;
419 SAVETMPS;
420
421 /* Put args on the stack */
422 PUSHMARK(SP);
423 for (ii=0; ii < len; ii++) {
424 XPUSHs(av_shift(params));
425 }
426 PUTBACK;
427
4dcb9e53 428 oldscope = PL_scopestack_ix;
429 JMPENV_PUSH(jmp_rc);
430 if (jmp_rc == 0) {
431 /* Run the specified function */
432 len = (int)call_sv(thread->init_function, thread->gimme|G_EVAL);
433 } else if (jmp_rc == 2) {
69a9b4b8 434 /* Thread exited */
435 exit_app = 1;
436 exit_code = STATUS_CURRENT;
4dcb9e53 437 while (PL_scopestack_ix > oldscope) {
438 LEAVE;
439 }
440 }
441 JMPENV_POP;
fc04eb16 442
443 /* Remove args from stack and put back in params array */
444 SPAGAIN;
445 for (ii=len-1; ii >= 0; ii--) {
446 SV *sv = POPs;
4dcb9e53 447 if (jmp_rc == 0) {
448 av_store(params, ii, SvREFCNT_inc(sv));
449 }
fc04eb16 450 }
451
4dcb9e53 452 FREETMPS;
453 LEAVE;
454
955c272e 455 /* Check for abnormal termination */
456 if (SvTRUE(ERRSV)) {
457 died = PERL_ITHR_DIED;
458 thread->err = newSVsv(ERRSV);
459 /* If ERRSV is an object, remember the classname and then
460 * rebless into 'main' so it will survive 'cloning'
461 */
462 if (sv_isobject(thread->err)) {
463 thread->err_class = HvNAME(SvSTASH(SvRV(thread->err)));
464 sv_bless(thread->err, gv_stashpv("main", 0));
465 }
466
467 if (ckWARN_d(WARN_THREADS)) {
468 oldscope = PL_scopestack_ix;
469 JMPENV_PUSH(jmp_rc);
470 if (jmp_rc == 0) {
471 /* Warn that thread died */
472 Perl_warn(aTHX_ "Thread %" UVuf " terminated abnormally: %" SVf, thread->tid, ERRSV);
473 } else if (jmp_rc == 2) {
474 /* Warn handler exited */
475 exit_app = 1;
476 exit_code = STATUS_CURRENT;
477 while (PL_scopestack_ix > oldscope) {
478 LEAVE;
479 }
4dcb9e53 480 }
955c272e 481 JMPENV_POP;
4dcb9e53 482 }
fc04eb16 483 }
484
fc04eb16 485 /* Release function ref */
486 SvREFCNT_dec(thread->init_function);
487 thread->init_function = Nullsv;
488 }
62375a60 489
fc04eb16 490 PerlIO_flush((PerlIO *)NULL);
491
5c6ff896 492 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
fc04eb16 493 MUTEX_LOCK(&thread->mutex);
494 /* Mark as finished */
955c272e 495 thread->state |= (PERL_ITHR_FINISHED | died);
69a9b4b8 496 /* Clear exit flag if required */
fea7688c 497 if (thread->state & PERL_ITHR_THREAD_EXIT_ONLY) {
69a9b4b8 498 exit_app = 0;
fea7688c 499 }
fc04eb16 500
69a9b4b8 501 /* Adjust thread status counts */
adc09a0e 502 if (thread->state & PERL_ITHR_DETACHED) {
5c6ff896 503 MY_POOL.detached_threads--;
4dcb9e53 504 } else {
5c6ff896 505 MY_POOL.running_threads--;
506 MY_POOL.joinable_threads++;
5168baf3 507 }
adc09a0e 508 MUTEX_UNLOCK(&thread->mutex);
5c6ff896 509 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
69a9b4b8 510
511 /* Exit application if required */
512 if (exit_app) {
513 oldscope = PL_scopestack_ix;
514 JMPENV_PUSH(jmp_rc);
515 if (jmp_rc == 0) {
516 /* Warn if there are unjoined threads */
517 S_exit_warning(aTHX);
518 } else if (jmp_rc == 2) {
519 /* Warn handler exited */
520 exit_code = STATUS_CURRENT;
521 while (PL_scopestack_ix > oldscope) {
522 LEAVE;
523 }
524 }
525 JMPENV_POP;
526
527 my_exit(exit_code);
528 }
529
adc09a0e 530 /* Try to clean up thread */
531 S_ithread_destruct(aTHX_ thread);
91604d21 532
47ba8780 533#ifdef WIN32
fc04eb16 534 return ((DWORD)0);
e8f2bb9a 535#else
fc04eb16 536 return (0);
47ba8780 537#endif
68795e93 538}
539
fc04eb16 540
541/* Type conversion helper functions */
fea7688c 542
861d5cbe 543STATIC SV *
544S_ithread_to_SV(pTHX_ SV *obj, ithread *thread, char *classname, bool inc)
68795e93 545{
546 SV *sv;
547 MAGIC *mg;
fc04eb16 548
9ca4d7fd 549 /* If incrementing thread ref count, then call within mutex lock */
68795e93 550 if (inc) {
fc04eb16 551 MUTEX_LOCK(&thread->mutex);
552 thread->count++;
553 MUTEX_UNLOCK(&thread->mutex);
554 }
555
556 if (! obj) {
557 obj = newSV(0);
68795e93 558 }
fc04eb16 559
560 sv = newSVrv(obj, classname);
561 sv_setiv(sv, PTR2IV(thread));
562 mg = sv_magicext(sv, Nullsv, PERL_MAGIC_shared_scalar, &ithread_vtbl, (char *)thread, 0);
68795e93 563 mg->mg_flags |= MGf_DUP;
564 SvREADONLY_on(sv);
fc04eb16 565
566 return (obj);
68795e93 567}
47ba8780 568
861d5cbe 569STATIC ithread *
570S_SV_to_ithread(pTHX_ SV *sv)
68795e93 571{
fc04eb16 572 /* Argument is a thread */
573 if (SvROK(sv)) {
574 return (INT2PTR(ithread *, SvIV(SvRV(sv))));
575 }
576 /* Argument is classname, therefore return current thread */
577 return (S_ithread_get(aTHX));
47ba8780 578}
579
47ba8780 580
fc04eb16 581/* threads->create()
582 * Called in context of parent thread.
5c6ff896 583 * Called with MY_POOL.create_destruct_mutex locked. (Unlocked on error.)
fc04eb16 584 */
861d5cbe 585STATIC ithread *
fc04eb16 586S_ithread_create(
9ca4d7fd 587 pTHX_ SV *init_function,
514612b7 588 IV stack_size,
9d9ff5b1 589 int gimme,
69a9b4b8 590 int exit_opt,
fc04eb16 591 SV *params)
68795e93 592{
fc04eb16 593 ithread *thread;
fc04eb16 594 ithread *current_thread = S_ithread_get(aTHX);
3b1c3273 595
fc04eb16 596 SV **tmps_tmp = PL_tmps_stack;
597 IV tmps_ix = PL_tmps_ix;
d94006e8 598#ifndef WIN32
fc04eb16 599 int rc_stack_size = 0;
600 int rc_thread_create = 0;
d94006e8 601#endif
adc09a0e 602 dMY_POOL;
3b1c3273 603
adc09a0e 604 /* Allocate thread structure in context of the main thread's interpreter */
5c6ff896 605 {
606 PERL_SET_CONTEXT(MY_POOL.main_thread.interp);
607 thread = (ithread *)PerlMemShared_malloc(sizeof(ithread));
608 }
609 PERL_SET_CONTEXT(aTHX);
fc04eb16 610 if (!thread) {
5c6ff896 611 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
fc04eb16 612 PerlLIO_write(PerlIO_fileno(Perl_error_log), PL_no_mem, strlen(PL_no_mem));
613 my_exit(1);
614 }
615 Zero(thread, 1, ithread);
616
617 /* Add to threads list */
5c6ff896 618 thread->next = &MY_POOL.main_thread;
619 thread->prev = MY_POOL.main_thread.prev;
620 MY_POOL.main_thread.prev = thread;
fc04eb16 621 thread->prev->next = thread;
c05ae023 622
fc04eb16 623 /* Set count to 1 immediately in case thread exits before
624 * we return to caller!
625 */
626 thread->count = 1;
627
9ca4d7fd 628 /* Block new thread until ->create() call finishes */
fc04eb16 629 MUTEX_INIT(&thread->mutex);
9ca4d7fd 630 MUTEX_LOCK(&thread->mutex);
631
5c6ff896 632 thread->tid = MY_POOL.tid_counter++;
861d5cbe 633 thread->stack_size = S_good_stack_size(aTHX_ stack_size);
9d9ff5b1 634 thread->gimme = gimme;
69a9b4b8 635 thread->state = exit_opt;
fc04eb16 636
637 /* "Clone" our interpreter into the thread's interpreter.
638 * This gives thread access to "static data" and code.
639 */
640 PerlIO_flush((PerlIO *)NULL);
641 S_ithread_set(aTHX_ thread);
642
643 SAVEBOOL(PL_srand_called); /* Save this so it becomes the correct value */
644 PL_srand_called = FALSE; /* Set it to false so we can detect if it gets
645 set during the clone */
3b1c3273 646
47ba8780 647#ifdef WIN32
fc04eb16 648 thread->interp = perl_clone(aTHX, CLONEf_KEEP_PTR_TABLE | CLONEf_CLONE_HOST);
47ba8780 649#else
fc04eb16 650 thread->interp = perl_clone(aTHX, CLONEf_KEEP_PTR_TABLE);
47ba8780 651#endif
47ba8780 652
fc04eb16 653 /* perl_clone() leaves us in new interpreter's context. As it is tricky
654 * to spot an implicit aTHX, create a new scope with aTHX matching the
655 * context for the duration of our work for new interpreter.
656 */
657 {
894eec8b 658 CLONE_PARAMS clone_param;
659
fc04eb16 660 dTHXa(thread->interp);
661
662 MY_CXT_CLONE;
663
664 /* Here we remove END blocks since they should only run in the thread
665 * they are created
666 */
667 SvREFCNT_dec(PL_endav);
668 PL_endav = newAV();
404aaa48 669
894eec8b 670 clone_param.flags = 0;
f2e0bb91 671 if (SvPOK(init_function)) {
672 thread->init_function = newSV(0);
673 sv_copypv(thread->init_function, init_function);
674 } else {
f2e0bb91 675 thread->init_function = sv_dup(init_function, &clone_param);
676 if (SvREFCNT(thread->init_function) == 0) {
d4315dd6 677 SvREFCNT_inc_void(thread->init_function);
f2e0bb91 678 }
fc04eb16 679 }
680
681 thread->params = sv_dup(params, &clone_param);
d4315dd6 682 SvREFCNT_inc_void(thread->params);
fc04eb16 683
684 /* The code below checks that anything living on the tmps stack and
685 * has been cloned (so it lives in the ptr_table) has a refcount
686 * higher than 0.
687 *
688 * If the refcount is 0 it means that a something on the stack/context
689 * was holding a reference to it and since we init_stacks() in
690 * perl_clone that won't get cleaned and we will get a leaked scalar.
691 * The reason it was cloned was that it lived on the @_ stack.
692 *
693 * Example of this can be found in bugreport 15837 where calls in the
694 * parameter list end up as a temp.
695 *
696 * One could argue that this fix should be in perl_clone.
697 */
698 while (tmps_ix > 0) {
699 SV* sv = (SV*)ptr_table_fetch(PL_ptr_table, tmps_tmp[tmps_ix]);
700 tmps_ix--;
701 if (sv && SvREFCNT(sv) == 0) {
d4315dd6 702 SvREFCNT_inc_void(sv);
fc04eb16 703 SvREFCNT_dec(sv);
704 }
705 }
706
707 SvTEMP_off(thread->init_function);
708 ptr_table_free(PL_ptr_table);
709 PL_ptr_table = NULL;
710 PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
711 }
712 S_ithread_set(aTHX_ current_thread);
713 PERL_SET_CONTEXT(aTHX);
714
715 /* Create/start the thread */
47ba8780 716#ifdef WIN32
fc04eb16 717 thread->handle = CreateThread(NULL,
514612b7 718 (DWORD)thread->stack_size,
fc04eb16 719 S_ithread_run,
720 (LPVOID)thread,
514612b7 721 STACK_SIZE_PARAM_IS_A_RESERVATION,
fc04eb16 722 &thread->thr);
82c40bf6 723#else
fc04eb16 724 {
861d5cbe 725 STATIC pthread_attr_t attr;
726 STATIC int attr_inited = 0;
727 STATIC int attr_joinable = PTHREAD_CREATE_JOINABLE;
fc04eb16 728 if (! attr_inited) {
729 pthread_attr_init(&attr);
730 attr_inited = 1;
731 }
732
fa26028c 733# ifdef PTHREAD_ATTR_SETDETACHSTATE
fc04eb16 734 /* Threads start out joinable */
735 PTHREAD_ATTR_SETDETACHSTATE(&attr, attr_joinable);
fa26028c 736# endif
fc04eb16 737
514612b7 738# ifdef _POSIX_THREAD_ATTR_STACKSIZE
fc04eb16 739 /* Set thread's stack size */
514612b7 740 if (thread->stack_size > 0) {
741 rc_stack_size = pthread_attr_setstacksize(&attr, (size_t)thread->stack_size);
742 }
3eb37d38 743# endif
744
fc04eb16 745 /* Create the thread */
746 if (! rc_stack_size) {
747# ifdef OLD_PTHREADS_API
748 rc_thread_create = pthread_create(&thread->thr,
749 attr,
750 S_ithread_run,
751 (void *)thread);
752# else
753# if defined(HAS_PTHREAD_ATTR_SETSCOPE) && defined(PTHREAD_SCOPE_SYSTEM)
754 pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);
755# endif
756 rc_thread_create = pthread_create(&thread->thr,
757 &attr,
758 S_ithread_run,
759 (void *)thread);
19a077f6 760# endif
fc04eb16 761 }
514612b7 762
763# ifdef _POSIX_THREAD_ATTR_STACKSIZE
764 /* Try to get thread's actual stack size */
765 {
766 size_t stacksize;
58a3a76c 767#ifdef HPUX1020
768 stacksize = pthread_attr_getstacksize(attr);
769#else
770 if (! pthread_attr_getstacksize(&attr, &stacksize))
771#endif
772 if (stacksize > 0) {
514612b7 773 thread->stack_size = (IV)stacksize;
774 }
514612b7 775 }
776# endif
fc04eb16 777 }
82c40bf6 778#endif
bcd9ca9b 779
fc04eb16 780 /* Check for errors */
d94006e8 781#ifdef WIN32
fc04eb16 782 if (thread->handle == NULL) {
d94006e8 783#else
fc04eb16 784 if (rc_stack_size || rc_thread_create) {
d94006e8 785#endif
9ca4d7fd 786 /* Must unlock mutex for destruct call */
5c6ff896 787 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
fc04eb16 788 sv_2mortal(params);
adc09a0e 789 thread->state |= PERL_ITHR_NONVIABLE;
fc04eb16 790 S_ithread_destruct(aTHX_ thread);
d94006e8 791#ifndef WIN32
514612b7 792 if (ckWARN_d(WARN_THREADS)) {
fea7688c 793 if (rc_stack_size) {
514612b7 794 Perl_warn(aTHX_ "Thread creation failed: pthread_attr_setstacksize(%" IVdf ") returned %d", thread->stack_size, rc_stack_size);
fea7688c 795 } else {
514612b7 796 Perl_warn(aTHX_ "Thread creation failed: pthread_create returned %d", rc_thread_create);
fea7688c 797 }
514612b7 798 }
d94006e8 799#endif
9ca4d7fd 800 return (NULL);
fc04eb16 801 }
802
5c6ff896 803 MY_POOL.running_threads++;
fc04eb16 804 sv_2mortal(params);
9ca4d7fd 805 return (thread);
68795e93 806}
47ba8780 807
73e09c8f 808#endif /* USE_ITHREADS */
e1c44605 809
fcea4b7c 810
fc04eb16 811MODULE = threads PACKAGE = threads PREFIX = ithread_
68795e93 812PROTOTYPES: DISABLE
8222d950 813
73e09c8f 814#ifdef USE_ITHREADS
815
68795e93 816void
f4cc38af 817ithread_create(...)
818 PREINIT:
819 char *classname;
514612b7 820 ithread *thread;
f4cc38af 821 SV *function_to_call;
822 AV *params;
514612b7 823 HV *specs;
824 IV stack_size;
9d9ff5b1 825 int context;
69a9b4b8 826 int exit_opt;
827 SV *thread_exit_only;
9d9ff5b1 828 char *str;
514612b7 829 int idx;
f4cc38af 830 int ii;
5c6ff896 831 dMY_POOL;
f4cc38af 832 CODE:
514612b7 833 if ((items >= 2) && SvROK(ST(1)) && SvTYPE(SvRV(ST(1)))==SVt_PVHV) {
fea7688c 834 if (--items < 2) {
514612b7 835 Perl_croak(aTHX_ "Usage: threads->create(\\%specs, function, ...)");
fea7688c 836 }
514612b7 837 specs = (HV*)SvRV(ST(1));
838 idx = 1;
839 } else {
fea7688c 840 if (items < 2) {
514612b7 841 Perl_croak(aTHX_ "Usage: threads->create(function, ...)");
fea7688c 842 }
514612b7 843 specs = NULL;
844 idx = 0;
845 }
f4cc38af 846
514612b7 847 if (sv_isobject(ST(0))) {
848 /* $thr->create() */
849 classname = HvNAME(SvSTASH(SvRV(ST(0))));
850 thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
8718f9a1 851 MUTEX_LOCK(&thread->mutex);
514612b7 852 stack_size = thread->stack_size;
69a9b4b8 853 exit_opt = thread->state & PERL_ITHR_THREAD_EXIT_ONLY;
8718f9a1 854 MUTEX_UNLOCK(&thread->mutex);
514612b7 855 } else {
856 /* threads->create() */
857 classname = (char *)SvPV_nolen(ST(0));
5c6ff896 858 stack_size = MY_POOL.default_stack_size;
69a9b4b8 859 thread_exit_only = get_sv("threads::thread_exit_only", TRUE);
860 exit_opt = (SvTRUE(thread_exit_only))
861 ? PERL_ITHR_THREAD_EXIT_ONLY : 0;
514612b7 862 }
863
864 function_to_call = ST(idx+1);
865
9d9ff5b1 866 context = -1;
514612b7 867 if (specs) {
868 /* stack_size */
869 if (hv_exists(specs, "stack", 5)) {
870 stack_size = SvIV(*hv_fetch(specs, "stack", 5, 0));
871 } else if (hv_exists(specs, "stacksize", 9)) {
872 stack_size = SvIV(*hv_fetch(specs, "stacksize", 9, 0));
873 } else if (hv_exists(specs, "stack_size", 10)) {
874 stack_size = SvIV(*hv_fetch(specs, "stack_size", 10, 0));
875 }
9d9ff5b1 876
877 /* context */
878 if (hv_exists(specs, "context", 7)) {
879 str = (char *)SvPV_nolen(*hv_fetch(specs, "context", 7, 0));
880 switch (*str) {
881 case 'a':
882 case 'A':
883 context = G_ARRAY;
884 break;
885 case 's':
886 case 'S':
887 context = G_SCALAR;
888 break;
889 case 'v':
890 case 'V':
891 context = G_VOID;
892 break;
893 default:
894 Perl_croak(aTHX_ "Invalid context: %s", str);
895 }
896 } else if (hv_exists(specs, "array", 5)) {
897 if (SvTRUE(*hv_fetch(specs, "array", 5, 0))) {
898 context = G_ARRAY;
899 }
900 } else if (hv_exists(specs, "scalar", 6)) {
901 if (SvTRUE(*hv_fetch(specs, "scalar", 6, 0))) {
902 context = G_SCALAR;
903 }
904 } else if (hv_exists(specs, "void", 4)) {
905 if (SvTRUE(*hv_fetch(specs, "void", 4, 0))) {
906 context = G_VOID;
907 }
908 }
69a9b4b8 909
910 /* exit => thread_only */
911 if (hv_exists(specs, "exit", 4)) {
912 str = (char *)SvPV_nolen(*hv_fetch(specs, "exit", 4, 0));
913 exit_opt = (*str == 't' || *str == 'T')
914 ? PERL_ITHR_THREAD_EXIT_ONLY : 0;
915 }
9d9ff5b1 916 }
917 if (context == -1) {
918 context = GIMME_V; /* Implicit context */
919 } else {
920 context |= (GIMME_V & (~(G_ARRAY|G_SCALAR|G_VOID)));
514612b7 921 }
f4cc38af 922
923 /* Function args */
924 params = newAV();
925 if (items > 2) {
514612b7 926 for (ii=2; ii < items ; ii++) {
927 av_push(params, SvREFCNT_inc(ST(idx+ii)));
f4cc38af 928 }
929 }
930
931 /* Create thread */
5c6ff896 932 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
9ca4d7fd 933 thread = S_ithread_create(aTHX_ function_to_call,
934 stack_size,
935 context,
936 exit_opt,
937 newRV_noinc((SV*)params));
938 if (! thread) {
939 XSRETURN_UNDEF; /* Mutex already unlocked */
940 }
861d5cbe 941 ST(0) = sv_2mortal(S_ithread_to_SV(aTHX_ Nullsv, thread, classname, FALSE));
adc09a0e 942 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
9ca4d7fd 943
944 /* Let thread run */
945 MUTEX_UNLOCK(&thread->mutex);
9ca4d7fd 946
f4cc38af 947 /* XSRETURN(1); - implied */
948
8222d950 949
68795e93 950void
f4cc38af 951ithread_list(...)
952 PREINIT:
953 char *classname;
fc04eb16 954 ithread *thread;
f4cc38af 955 int list_context;
956 IV count = 0;
11db694d 957 int want_running = 0;
8718f9a1 958 int state;
5c6ff896 959 dMY_POOL;
f4cc38af 960 PPCODE:
961 /* Class method only */
fea7688c 962 if (SvROK(ST(0))) {
ead32952 963 Perl_croak(aTHX_ "Usage: threads->list(...)");
fea7688c 964 }
f4cc38af 965 classname = (char *)SvPV_nolen(ST(0));
966
967 /* Calling context */
968 list_context = (GIMME_V == G_ARRAY);
969
ead32952 970 /* Running or joinable parameter */
971 if (items > 1) {
972 want_running = SvTRUE(ST(1));
973 }
974
f4cc38af 975 /* Walk through threads list */
5c6ff896 976 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
977 for (thread = MY_POOL.main_thread.next;
978 thread != &MY_POOL.main_thread;
fc04eb16 979 thread = thread->next)
f4cc38af 980 {
8718f9a1 981 MUTEX_LOCK(&thread->mutex);
982 state = thread->state;
983 MUTEX_UNLOCK(&thread->mutex);
984
f4cc38af 985 /* Ignore detached or joined threads */
8718f9a1 986 if (state & PERL_ITHR_UNCALLABLE) {
f4cc38af 987 continue;
988 }
ead32952 989
990 /* Filter per parameter */
991 if (items > 1) {
992 if (want_running) {
8718f9a1 993 if (state & PERL_ITHR_FINISHED) {
ead32952 994 continue; /* Not running */
995 }
996 } else {
8718f9a1 997 if (! (state & PERL_ITHR_FINISHED)) {
ead32952 998 continue; /* Still running - not joinable yet */
999 }
1000 }
1001 }
1002
f4cc38af 1003 /* Push object on stack if list context */
1004 if (list_context) {
861d5cbe 1005 XPUSHs(sv_2mortal(S_ithread_to_SV(aTHX_ Nullsv, thread, classname, TRUE)));
f4cc38af 1006 }
1007 count++;
1008 }
5c6ff896 1009 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
f4cc38af 1010 /* If scalar context, send back count */
1011 if (! list_context) {
1012 XSRETURN_IV(count);
1013 }
678a9b6c 1014
1015
1016void
f4cc38af 1017ithread_self(...)
1018 PREINIT:
1019 char *classname;
fcea4b7c 1020 ithread *thread;
f4cc38af 1021 CODE:
1022 /* Class method only */
11db694d 1023 if ((items != 1) || SvROK(ST(0))) {
f4cc38af 1024 Perl_croak(aTHX_ "Usage: threads->self()");
fea7688c 1025 }
f4cc38af 1026 classname = (char *)SvPV_nolen(ST(0));
1027
fcea4b7c 1028 thread = S_ithread_get(aTHX);
1029
861d5cbe 1030 ST(0) = sv_2mortal(S_ithread_to_SV(aTHX_ Nullsv, thread, classname, TRUE));
f4cc38af 1031 /* XSRETURN(1); - implied */
47ba8780 1032
47ba8780 1033
1034void
f4cc38af 1035ithread_tid(...)
1036 PREINIT:
1037 ithread *thread;
1038 CODE:
11db694d 1039 PERL_UNUSED_VAR(items);
861d5cbe 1040 thread = S_SV_to_ithread(aTHX_ ST(0));
f4cc38af 1041 XST_mUV(0, thread->tid);
1042 /* XSRETURN(1); - implied */
1043
e1c44605 1044
f9dff5f5 1045void
f4cc38af 1046ithread_join(...)
1047 PREINIT:
fcea4b7c 1048 ithread *thread;
8718f9a1 1049 ithread *current_thread;
fcea4b7c 1050 int join_err;
f4cc38af 1051 AV *params;
1052 int len;
1053 int ii;
fcea4b7c 1054#ifdef WIN32
1055 DWORD waitcode;
1056#else
8718f9a1 1057 int rc_join;
fcea4b7c 1058 void *retval;
1059#endif
5c6ff896 1060 dMY_POOL;
f4cc38af 1061 PPCODE:
1062 /* Object method only */
11db694d 1063 if ((items != 1) || ! sv_isobject(ST(0))) {
f4cc38af 1064 Perl_croak(aTHX_ "Usage: $thr->join()");
fea7688c 1065 }
f4cc38af 1066
8718f9a1 1067 /* Check if the thread is joinable and not ourselves */
861d5cbe 1068 thread = S_SV_to_ithread(aTHX_ ST(0));
8718f9a1 1069 current_thread = S_ithread_get(aTHX);
1070
1071 MUTEX_LOCK(&thread->mutex);
1072 if ((join_err = (thread->state & PERL_ITHR_UNCALLABLE))) {
1073 MUTEX_UNLOCK(&thread->mutex);
1074 Perl_croak(aTHX_ (join_err & PERL_ITHR_DETACHED)
1075 ? "Cannot join a detached thread"
1076 : "Thread already joined");
1077 } else if (thread->tid == current_thread->tid) {
1078 MUTEX_UNLOCK(&thread->mutex);
1079 Perl_croak(aTHX_ "Cannot join self");
fcea4b7c 1080 }
1081
8718f9a1 1082 /* Mark as joined */
1083 thread->state |= PERL_ITHR_JOINED;
1084 MUTEX_UNLOCK(&thread->mutex);
1085
1086 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
1087 MY_POOL.joinable_threads--;
1088 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
1089
fcea4b7c 1090 /* Join the thread */
1091#ifdef WIN32
8718f9a1 1092 if (WaitForSingleObject(thread->handle, INFINITE) != WAIT_OBJECT_0) {
1093 /* Timeout/abandonment unexpected here; check $^E */
1094 Perl_croak(aTHX_ "PANIC: underlying join failed");
1095 };
fcea4b7c 1096#else
8718f9a1 1097 if ((rc_join = pthread_join(thread->thr, &retval)) != 0) {
1098 /* In progress/deadlock/unknown unexpected here; check $! */
1099 errno = rc_join;
1100 Perl_croak(aTHX_ "PANIC: underlying join failed");
1101 };
fcea4b7c 1102#endif
1103
1104 MUTEX_LOCK(&thread->mutex);
fcea4b7c 1105 /* Get the return value from the call_sv */
955c272e 1106 /* Objects do not survive this process - FIXME */
fcea4b7c 1107 {
1108 AV *params_copy;
1109 PerlInterpreter *other_perl;
1110 CLONE_PARAMS clone_params;
fcea4b7c 1111
1112 params_copy = (AV *)SvRV(thread->params);
1113 other_perl = thread->interp;
1114 clone_params.stashes = newAV();
1115 clone_params.flags = CLONEf_JOIN_IN;
1116 PL_ptr_table = ptr_table_new();
fcea4b7c 1117 S_ithread_set(aTHX_ thread);
1118 /* Ensure 'meaningful' addresses retain their meaning */
1119 ptr_table_store(PL_ptr_table, &other_perl->Isv_undef, &PL_sv_undef);
1120 ptr_table_store(PL_ptr_table, &other_perl->Isv_no, &PL_sv_no);
1121 ptr_table_store(PL_ptr_table, &other_perl->Isv_yes, &PL_sv_yes);
1122 params = (AV *)sv_dup((SV*)params_copy, &clone_params);
1123 S_ithread_set(aTHX_ current_thread);
1124 SvREFCNT_dec(clone_params.stashes);
d4315dd6 1125 SvREFCNT_inc_void(params);
fcea4b7c 1126 ptr_table_free(PL_ptr_table);
1127 PL_ptr_table = NULL;
1128 }
1129
955c272e 1130 /* If thread didn't die, then we can free its interpreter */
1131 if (! (thread->state & PERL_ITHR_DIED)) {
1132 S_ithread_clear(aTHX_ thread);
1133 }
fcea4b7c 1134 MUTEX_UNLOCK(&thread->mutex);
1135
955c272e 1136 /* Try to cleanup thread */
1137 S_ithread_destruct(aTHX_ thread);
1138
fcea4b7c 1139 /* If no return values, then just return */
f4cc38af 1140 if (! params) {
1141 XSRETURN_UNDEF;
1142 }
1143
1144 /* Put return values on stack */
1145 len = (int)AvFILL(params);
1146 for (ii=0; ii <= len; ii++) {
1147 SV* param = av_shift(params);
1148 XPUSHs(sv_2mortal(param));
1149 }
1150
1151 /* Free return value array */
1152 SvREFCNT_dec(params);
1153
1154
1155void
1156ithread_yield(...)
1157 CODE:
11db694d 1158 PERL_UNUSED_VAR(items);
f4cc38af 1159 YIELD;
1160
1161
1162void
1163ithread_detach(...)
1164 PREINIT:
1165 ithread *thread;
fcea4b7c 1166 int detach_err;
5c6ff896 1167 dMY_POOL;
f4cc38af 1168 CODE:
11db694d 1169 PERL_UNUSED_VAR(items);
1170
fcea4b7c 1171 /* Detach the thread */
8718f9a1 1172 thread = S_SV_to_ithread(aTHX_ ST(0));
5c6ff896 1173 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
9ca4d7fd 1174 MUTEX_LOCK(&thread->mutex);
8718f9a1 1175 if (! (detach_err = (thread->state & PERL_ITHR_UNCALLABLE))) {
1176 /* Thread is detachable */
1177 thread->state |= PERL_ITHR_DETACHED;
fcea4b7c 1178#ifdef WIN32
8718f9a1 1179 /* Windows has no 'detach thread' function */
fcea4b7c 1180#else
8718f9a1 1181 PERL_THREAD_DETACH(thread->thr);
fcea4b7c 1182#endif
8718f9a1 1183 if (thread->state & PERL_ITHR_FINISHED) {
1184 MY_POOL.joinable_threads--;
1185 } else {
1186 MY_POOL.running_threads--;
1187 MY_POOL.detached_threads++;
1188 }
4dcb9e53 1189 }
adc09a0e 1190 MUTEX_UNLOCK(&thread->mutex);
5c6ff896 1191 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
4dcb9e53 1192
8718f9a1 1193 if (detach_err) {
1194 Perl_croak(aTHX_ (detach_err & PERL_ITHR_DETACHED)
1195 ? "Thread already detached"
1196 : "Cannot detach a joined thread");
1197 }
1198
955c272e 1199 /* If thread is finished and didn't die,
1200 * then we can free its interpreter */
1201 MUTEX_LOCK(&thread->mutex);
1202 if ((thread->state & PERL_ITHR_FINISHED) &&
1203 ! (thread->state & PERL_ITHR_DIED))
1204 {
1205 S_ithread_clear(aTHX_ thread);
1206 }
1207 MUTEX_UNLOCK(&thread->mutex);
1208
adc09a0e 1209 /* Try to cleanup thread */
1210 S_ithread_destruct(aTHX_ thread);
f4cc38af 1211
47ba8780 1212
1213void
c0003851 1214ithread_kill(...)
1215 PREINIT:
1216 ithread *thread;
1217 char *sig_name;
1218 IV signal;
1219 CODE:
1220 /* Must have safe signals */
fea7688c 1221 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG) {
4dcb9e53 1222 Perl_croak(aTHX_ "Cannot signal threads without safe signals");
fea7688c 1223 }
c0003851 1224
1225 /* Object method only */
11db694d 1226 if ((items != 2) || ! sv_isobject(ST(0))) {
c0003851 1227 Perl_croak(aTHX_ "Usage: $thr->kill('SIG...')");
fea7688c 1228 }
c0003851 1229
c0003851 1230 /* Get signal */
1231 sig_name = SvPV_nolen(ST(1));
1232 if (isALPHA(*sig_name)) {
fea7688c 1233 if (*sig_name == 'S' && sig_name[1] == 'I' && sig_name[2] == 'G') {
c0003851 1234 sig_name += 3;
fea7688c 1235 }
1236 if ((signal = whichsig(sig_name)) < 0) {
c0003851 1237 Perl_croak(aTHX_ "Unrecognized signal name: %s", sig_name);
fea7688c 1238 }
1239 } else {
c0003851 1240 signal = SvIV(ST(1));
fea7688c 1241 }
c0003851 1242
1243 /* Set the signal for the thread */
861d5cbe 1244 thread = S_SV_to_ithread(aTHX_ ST(0));
4dcb9e53 1245 MUTEX_LOCK(&thread->mutex);
3ceb02cd 1246 if (thread->interp) {
c0003851 1247 dTHXa(thread->interp);
1248 PL_psig_pend[signal]++;
1249 PL_sig_pending = 1;
1250 }
4dcb9e53 1251 MUTEX_UNLOCK(&thread->mutex);
c0003851 1252
1253 /* Return the thread to allow for method chaining */
1254 ST(0) = ST(0);
1255 /* XSRETURN(1); - implied */
1256
1257
1258void
f4cc38af 1259ithread_DESTROY(...)
1260 CODE:
11db694d 1261 PERL_UNUSED_VAR(items);
fcea4b7c 1262 sv_unmagic(SvRV(ST(0)), PERL_MAGIC_shared_scalar);
f4cc38af 1263
1264
1265void
1266ithread_equal(...)
fc04eb16 1267 PREINIT:
1268 int are_equal = 0;
f4cc38af 1269 CODE:
11db694d 1270 PERL_UNUSED_VAR(items);
1271
fc04eb16 1272 /* Compares TIDs to determine thread equality */
f4cc38af 1273 if (sv_isobject(ST(0)) && sv_isobject(ST(1))) {
1274 ithread *thr1 = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1275 ithread *thr2 = INT2PTR(ithread *, SvIV(SvRV(ST(1))));
fc04eb16 1276 are_equal = (thr1->tid == thr2->tid);
1277 }
1278 if (are_equal) {
1279 XST_mYES(0);
f4cc38af 1280 } else {
fc04eb16 1281 /* Return 0 on false for backward compatibility */
f4cc38af 1282 XST_mIV(0, 0);
1283 }
1284 /* XSRETURN(1); - implied */
1285
47ba8780 1286
47ba8780 1287void
f4cc38af 1288ithread_object(...)
1289 PREINIT:
1290 char *classname;
1291 UV tid;
fc04eb16 1292 ithread *thread;
8718f9a1 1293 int state;
9ca4d7fd 1294 int have_obj = 0;
5c6ff896 1295 dMY_POOL;
f4cc38af 1296 CODE:
1297 /* Class method only */
fea7688c 1298 if (SvROK(ST(0))) {
f4cc38af 1299 Perl_croak(aTHX_ "Usage: threads->object($tid)");
fea7688c 1300 }
f4cc38af 1301 classname = (char *)SvPV_nolen(ST(0));
1302
1303 if ((items < 2) || ! SvOK(ST(1))) {
1304 XSRETURN_UNDEF;
1305 }
1306
fc04eb16 1307 /* threads->object($tid) */
f4cc38af 1308 tid = SvUV(ST(1));
1309
1310 /* Walk through threads list */
5c6ff896 1311 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
1312 for (thread = MY_POOL.main_thread.next;
1313 thread != &MY_POOL.main_thread;
fc04eb16 1314 thread = thread->next)
f4cc38af 1315 {
9ca4d7fd 1316 /* Look for TID */
1317 if (thread->tid == tid) {
1318 /* Ignore if detached or joined */
8718f9a1 1319 MUTEX_LOCK(&thread->mutex);
1320 state = thread->state;
1321 MUTEX_UNLOCK(&thread->mutex);
1322 if (! (state & PERL_ITHR_UNCALLABLE)) {
9ca4d7fd 1323 /* Put object on stack */
861d5cbe 1324 ST(0) = sv_2mortal(S_ithread_to_SV(aTHX_ Nullsv, thread, classname, TRUE));
9ca4d7fd 1325 have_obj = 1;
1326 }
1327 break;
f4cc38af 1328 }
f4cc38af 1329 }
5c6ff896 1330 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
9ca4d7fd 1331
1332 if (! have_obj) {
f4cc38af 1333 XSRETURN_UNDEF;
1334 }
1335 /* XSRETURN(1); - implied */
1336
1337
1338void
1339ithread__handle(...);
1340 PREINIT:
1341 ithread *thread;
1342 CODE:
11db694d 1343 PERL_UNUSED_VAR(items);
861d5cbe 1344 thread = S_SV_to_ithread(aTHX_ ST(0));
f4cc38af 1345#ifdef WIN32
fcea4b7c 1346 XST_mUV(0, PTR2UV(&thread->handle));
f4cc38af 1347#else
75ba4ae2 1348 XST_mUV(0, PTR2UV(&thread->thr));
f4cc38af 1349#endif
1350 /* XSRETURN(1); - implied */
68795e93 1351
514612b7 1352
1353void
1354ithread_get_stack_size(...)
1355 PREINIT:
1356 IV stack_size;
5c6ff896 1357 dMY_POOL;
514612b7 1358 CODE:
11db694d 1359 PERL_UNUSED_VAR(items);
514612b7 1360 if (sv_isobject(ST(0))) {
1361 /* $thr->get_stack_size() */
1362 ithread *thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1363 stack_size = thread->stack_size;
1364 } else {
1365 /* threads->get_stack_size() */
5c6ff896 1366 stack_size = MY_POOL.default_stack_size;
514612b7 1367 }
1368 XST_mIV(0, stack_size);
1369 /* XSRETURN(1); - implied */
1370
1371
1372void
1373ithread_set_stack_size(...)
1374 PREINIT:
1375 IV old_size;
5c6ff896 1376 dMY_POOL;
514612b7 1377 CODE:
fea7688c 1378 if (items != 2) {
514612b7 1379 Perl_croak(aTHX_ "Usage: threads->set_stack_size($size)");
fea7688c 1380 }
1381 if (sv_isobject(ST(0))) {
514612b7 1382 Perl_croak(aTHX_ "Cannot change stack size of an existing thread");
fea7688c 1383 }
514612b7 1384
5c6ff896 1385 old_size = MY_POOL.default_stack_size;
1386 MY_POOL.default_stack_size = S_good_stack_size(aTHX_ SvIV(ST(1)));
514612b7 1387 XST_mIV(0, old_size);
1388 /* XSRETURN(1); - implied */
1389
ead32952 1390
1391void
1392ithread_is_running(...)
1393 PREINIT:
1394 ithread *thread;
1395 CODE:
1396 /* Object method only */
11db694d 1397 if ((items != 1) || ! sv_isobject(ST(0))) {
ead32952 1398 Perl_croak(aTHX_ "Usage: $thr->is_running()");
fea7688c 1399 }
ead32952 1400
1401 thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
8718f9a1 1402 MUTEX_LOCK(&thread->mutex);
ead32952 1403 ST(0) = (thread->state & PERL_ITHR_FINISHED) ? &PL_sv_no : &PL_sv_yes;
8718f9a1 1404 MUTEX_UNLOCK(&thread->mutex);
ead32952 1405 /* XSRETURN(1); - implied */
1406
1407
1408void
1409ithread_is_detached(...)
1410 PREINIT:
1411 ithread *thread;
1412 CODE:
11db694d 1413 PERL_UNUSED_VAR(items);
861d5cbe 1414 thread = S_SV_to_ithread(aTHX_ ST(0));
8718f9a1 1415 MUTEX_LOCK(&thread->mutex);
ead32952 1416 ST(0) = (thread->state & PERL_ITHR_DETACHED) ? &PL_sv_yes : &PL_sv_no;
8718f9a1 1417 MUTEX_UNLOCK(&thread->mutex);
ead32952 1418 /* XSRETURN(1); - implied */
1419
1420
1421void
1422ithread_is_joinable(...)
1423 PREINIT:
1424 ithread *thread;
1425 CODE:
1426 /* Object method only */
11db694d 1427 if ((items != 1) || ! sv_isobject(ST(0))) {
ead32952 1428 Perl_croak(aTHX_ "Usage: $thr->is_joinable()");
fea7688c 1429 }
ead32952 1430
1431 thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1432 MUTEX_LOCK(&thread->mutex);
1433 ST(0) = ((thread->state & PERL_ITHR_FINISHED) &&
8718f9a1 1434 ! (thread->state & PERL_ITHR_UNCALLABLE))
ead32952 1435 ? &PL_sv_yes : &PL_sv_no;
1436 MUTEX_UNLOCK(&thread->mutex);
1437 /* XSRETURN(1); - implied */
1438
1439
1440void
1441ithread_wantarray(...)
1442 PREINIT:
1443 ithread *thread;
1444 CODE:
11db694d 1445 PERL_UNUSED_VAR(items);
861d5cbe 1446 thread = S_SV_to_ithread(aTHX_ ST(0));
ead32952 1447 ST(0) = (thread->gimme & G_ARRAY) ? &PL_sv_yes :
1448 (thread->gimme & G_VOID) ? &PL_sv_undef
1449 /* G_SCALAR */ : &PL_sv_no;
ead32952 1450 /* XSRETURN(1); - implied */
1451
69a9b4b8 1452
1453void
1454ithread_set_thread_exit_only(...)
1455 PREINIT:
1456 ithread *thread;
1457 CODE:
fea7688c 1458 if (items != 2) {
69a9b4b8 1459 Perl_croak(aTHX_ "Usage: ->set_thread_exit_only(boolean)");
fea7688c 1460 }
861d5cbe 1461 thread = S_SV_to_ithread(aTHX_ ST(0));
69a9b4b8 1462 MUTEX_LOCK(&thread->mutex);
1463 if (SvTRUE(ST(1))) {
1464 thread->state |= PERL_ITHR_THREAD_EXIT_ONLY;
1465 } else {
1466 thread->state &= ~PERL_ITHR_THREAD_EXIT_ONLY;
1467 }
1468 MUTEX_UNLOCK(&thread->mutex);
1469
955c272e 1470
1471void
1472ithread_error(...)
1473 PREINIT:
1474 ithread *thread;
1475 SV *err = NULL;
1476 CODE:
1477 /* Object method only */
1478 if ((items != 1) || ! sv_isobject(ST(0))) {
1479 Perl_croak(aTHX_ "Usage: $thr->err()");
1480 }
1481
1482 thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1483 MUTEX_LOCK(&thread->mutex);
1484
1485 /* If thread died, then clone the error into the calling thread */
1486 if (thread->state & PERL_ITHR_DIED) {
1487 PerlInterpreter *other_perl;
1488 CLONE_PARAMS clone_params;
1489 ithread *current_thread;
1490
1491 other_perl = thread->interp;
1492 clone_params.stashes = newAV();
1493 clone_params.flags = CLONEf_JOIN_IN;
1494 PL_ptr_table = ptr_table_new();
1495 current_thread = S_ithread_get(aTHX);
1496 S_ithread_set(aTHX_ thread);
1497 /* Ensure 'meaningful' addresses retain their meaning */
1498 ptr_table_store(PL_ptr_table, &other_perl->Isv_undef, &PL_sv_undef);
1499 ptr_table_store(PL_ptr_table, &other_perl->Isv_no, &PL_sv_no);
1500 ptr_table_store(PL_ptr_table, &other_perl->Isv_yes, &PL_sv_yes);
1501 err = sv_dup(thread->err, &clone_params);
1502 S_ithread_set(aTHX_ current_thread);
1503 SvREFCNT_dec(clone_params.stashes);
1504 SvREFCNT_inc_void(err);
1505 /* If error was an object, bless it into the correct class */
1506 if (thread->err_class) {
1507 sv_bless(err, gv_stashpv(thread->err_class, 1));
1508 }
1509 ptr_table_free(PL_ptr_table);
1510 PL_ptr_table = NULL;
1511 }
1512
1513 MUTEX_UNLOCK(&thread->mutex);
1514
1515 if (! err) {
1516 XSRETURN_UNDEF;
1517 }
1518
1519 ST(0) = sv_2mortal(err);
1520 /* XSRETURN(1); - implied */
1521
1522
73e09c8f 1523#endif /* USE_ITHREADS */
1524
fc04eb16 1525
68795e93 1526BOOT:
1527{
73e09c8f 1528#ifdef USE_ITHREADS
5c6ff896 1529 SV *my_pool_sv = *hv_fetch(PL_modglobal, MY_POOL_KEY,
1530 sizeof(MY_POOL_KEY)-1, TRUE);
1531 my_pool_t *my_poolp = (my_pool_t*)SvPVX(newSV(sizeof(my_pool_t)-1));
1532
fc04eb16 1533 MY_CXT_INIT;
1534
5c6ff896 1535 Zero(my_poolp, 1, my_pool_t);
1536 sv_setuv(my_pool_sv, PTR2UV(my_poolp));
1537
fc04eb16 1538 PL_perl_destruct_level = 2;
5c6ff896 1539 MUTEX_INIT(&MY_POOL.create_destruct_mutex);
1540 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
fc04eb16 1541
1542 PL_threadhook = &Perl_ithread_hook;
1543
5c6ff896 1544 MY_POOL.tid_counter = 1;
1545# ifdef THREAD_CREATE_NEEDS_STACK
1546 MY_POOL.default_stack_size = THREAD_CREATE_NEEDS_STACK;
1547# endif
1548
c372d929 1549 /* The 'main' thread is thread 0.
1550 * It is detached (unjoinable) and immortal.
1551 */
fc04eb16 1552
5c6ff896 1553 MUTEX_INIT(&MY_POOL.main_thread.mutex);
fc04eb16 1554
1555 /* Head of the threads list */
5c6ff896 1556 MY_POOL.main_thread.next = &MY_POOL.main_thread;
1557 MY_POOL.main_thread.prev = &MY_POOL.main_thread;
fc04eb16 1558
5c6ff896 1559 MY_POOL.main_thread.count = 1; /* Immortal */
fc04eb16 1560
5c6ff896 1561 MY_POOL.main_thread.interp = aTHX;
1562 MY_POOL.main_thread.state = PERL_ITHR_DETACHED; /* Detached */
1563 MY_POOL.main_thread.stack_size = MY_POOL.default_stack_size;
fc04eb16 1564# ifdef WIN32
5c6ff896 1565 MY_POOL.main_thread.thr = GetCurrentThreadId();
fc04eb16 1566# else
5c6ff896 1567 MY_POOL.main_thread.thr = pthread_self();
fc04eb16 1568# endif
1569
5c6ff896 1570 S_ithread_set(aTHX_ &MY_POOL.main_thread);
1571 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
73e09c8f 1572#endif /* USE_ITHREADS */
68795e93 1573}