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