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