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