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