This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Build fixes for Win32 after the Coverity smoke.
[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);
fa9804ae
JH
717 {
718 int fd = PerlIO_fileno(Perl_error_log);
719 if (fd >= 0) {
720 /* If there's no error_log, we cannot scream about it missing. */
721 PERL_UNUSED_RESULT(PerlLIO_write(fd, PL_no_mem, strlen(PL_no_mem)));
722 }
375ed12a 723 }
fc04eb16
JH
724 my_exit(1);
725 }
726 Zero(thread, 1, ithread);
727
728 /* Add to threads list */
5c6ff896
JH
729 thread->next = &MY_POOL.main_thread;
730 thread->prev = MY_POOL.main_thread.prev;
731 MY_POOL.main_thread.prev = thread;
fc04eb16 732 thread->prev->next = thread;
e9a908c9 733 MY_POOL.total_threads++;
c05ae023 734
6ebc233e 735 /* 1 ref to be held by the local var 'thread' in S_ithread_run().
6158f8b3 736 * 1 ref to be held by the threads object that we assume we will
6ebc233e
RGS
737 * be embedded in upon our return.
738 * 1 ref to be the responsibility of join/detach, so we don't get
739 * freed until join/detach, even if no thread objects remain.
740 * This allows the following to work:
878090d5 741 * { threads->create(sub{...}); } threads->object(1)->join;
fc04eb16 742 */
6158f8b3 743 thread->count = 3;
fc04eb16 744
9ca4d7fd 745 /* Block new thread until ->create() call finishes */
fc04eb16 746 MUTEX_INIT(&thread->mutex);
9ca4d7fd
JH
747 MUTEX_LOCK(&thread->mutex);
748
5c6ff896 749 thread->tid = MY_POOL.tid_counter++;
861d5cbe 750 thread->stack_size = S_good_stack_size(aTHX_ stack_size);
9d9ff5b1 751 thread->gimme = gimme;
69a9b4b8 752 thread->state = exit_opt;
fc04eb16
JH
753
754 /* "Clone" our interpreter into the thread's interpreter.
755 * This gives thread access to "static data" and code.
756 */
757 PerlIO_flush((PerlIO *)NULL);
758 S_ithread_set(aTHX_ thread);
759
760 SAVEBOOL(PL_srand_called); /* Save this so it becomes the correct value */
761 PL_srand_called = FALSE; /* Set it to false so we can detect if it gets
762 set during the clone */
3b1c3273 763
8264cf32 764#ifndef WIN32
b762d866
JW
765 /* perl_clone() will leave us the new interpreter's context. This poses
766 * two problems for our signal handler. First, it sets the new context
767 * before the new interpreter struct is fully initialized, so our signal
768 * handler might find bogus data in the interpreter struct it gets.
769 * Second, even if the interpreter is initialized before a signal comes in,
770 * we would like to avoid that interpreter receiving notifications for
771 * signals (especially when they ought to be for the one running in this
772 * thread), until it is running in its own thread. Another problem is that
773 * the new thread will not have set the context until some time after it
774 * has started, so it won't be safe for our signal handler to run until
775 * that time.
776 *
777 * So we block most signals here, so the new thread will inherit the signal
778 * mask, and unblock them right after the thread creation. The original
779 * mask is saved in the thread struct so that the new thread can restore
780 * the original mask.
781 */
782 S_block_most_signals(&thread->initial_sigmask);
8264cf32 783#endif
b762d866 784
47ba8780 785#ifdef WIN32
fc04eb16 786 thread->interp = perl_clone(aTHX, CLONEf_KEEP_PTR_TABLE | CLONEf_CLONE_HOST);
47ba8780 787#else
fc04eb16 788 thread->interp = perl_clone(aTHX, CLONEf_KEEP_PTR_TABLE);
47ba8780 789#endif
47ba8780 790
fc04eb16
JH
791 /* perl_clone() leaves us in new interpreter's context. As it is tricky
792 * to spot an implicit aTHX, create a new scope with aTHX matching the
793 * context for the duration of our work for new interpreter.
794 */
795 {
447f000e 796#if (PERL_VERSION > 13) || (PERL_VERSION == 13 && PERL_SUBVERSION > 1)
f7abe70b 797 CLONE_PARAMS *clone_param = Perl_clone_params_new(aTHX, thread->interp);
447f000e 798#else
680818c0
NC
799 CLONE_PARAMS clone_param_s;
800 CLONE_PARAMS *clone_param = &clone_param_s;
447f000e 801#endif
fc04eb16
JH
802 dTHXa(thread->interp);
803
804 MY_CXT_CLONE;
805
ab0dc2a1
NC
806#if (PERL_VERSION < 13) || (PERL_VERSION == 13 && PERL_SUBVERSION <= 1)
807 clone_param->flags = 0;
808#endif
809
fc04eb16
JH
810 /* Here we remove END blocks since they should only run in the thread
811 * they are created
812 */
813 SvREFCNT_dec(PL_endav);
39f3f7f4 814 PL_endav = NULL;
404aaa48 815
f2e0bb91
JH
816 if (SvPOK(init_function)) {
817 thread->init_function = newSV(0);
818 sv_copypv(thread->init_function, init_function);
819 } else {
f7abe70b 820 thread->init_function = sv_dup_inc(init_function, clone_param);
fc04eb16
JH
821 }
822
4cf5eae5 823 thread->params = params = newAV();
680818c0
NC
824 av_extend(params, num_params - 1);
825 AvFILLp(params) = num_params - 1;
4cf5eae5 826 array = AvARRAY(params);
680818c0
NC
827
828 /* params_start is an offset onto the Perl stack. This can be
829 reallocated (and hence move) as a side effect of calls to
830 perl_clone() and sv_dup_inc(). Hence copy the parameters
831 somewhere under our control first, before duplicating. */
832#if (PERL_VERSION > 8)
833 Copy(parent_perl->Istack_base + params_start, array, num_params, SV *);
834#else
835 Copy(parent_perl->Tstack_base + params_start, array, num_params, SV *);
836#endif
837 while (num_params--) {
838 *array = sv_dup_inc(*array, clone_param);
839 ++array;
4cf5eae5 840 }
447f000e 841#if (PERL_VERSION > 13) || (PERL_VERSION == 13 && PERL_SUBVERSION > 1)
dfa4c013
JH
842 Perl_clone_params_del(clone_param);
843#endif
fc04eb16 844
24855dff 845#if PERL_VERSION <= 8 && PERL_SUBVERSION <= 7
fc04eb16
JH
846 /* The code below checks that anything living on the tmps stack and
847 * has been cloned (so it lives in the ptr_table) has a refcount
848 * higher than 0.
849 *
850 * If the refcount is 0 it means that a something on the stack/context
851 * was holding a reference to it and since we init_stacks() in
852 * perl_clone that won't get cleaned and we will get a leaked scalar.
853 * The reason it was cloned was that it lived on the @_ stack.
854 *
855 * Example of this can be found in bugreport 15837 where calls in the
856 * parameter list end up as a temp.
857 *
24855dff 858 * As of 5.8.8 this is done in perl_clone.
fc04eb16
JH
859 */
860 while (tmps_ix > 0) {
861 SV* sv = (SV*)ptr_table_fetch(PL_ptr_table, tmps_tmp[tmps_ix]);
862 tmps_ix--;
863 if (sv && SvREFCNT(sv) == 0) {
d4315dd6 864 SvREFCNT_inc_void(sv);
fc04eb16
JH
865 SvREFCNT_dec(sv);
866 }
867 }
24855dff 868#endif
fc04eb16
JH
869
870 SvTEMP_off(thread->init_function);
871 ptr_table_free(PL_ptr_table);
872 PL_ptr_table = NULL;
873 PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
874 }
875 S_ithread_set(aTHX_ current_thread);
876 PERL_SET_CONTEXT(aTHX);
877
878 /* Create/start the thread */
47ba8780 879#ifdef WIN32
fc04eb16 880 thread->handle = CreateThread(NULL,
514612b7 881 (DWORD)thread->stack_size,
fc04eb16
JH
882 S_ithread_run,
883 (LPVOID)thread,
514612b7 884 STACK_SIZE_PARAM_IS_A_RESERVATION,
fc04eb16 885 &thread->thr);
82c40bf6 886#else
fc04eb16 887 {
861d5cbe
JH
888 STATIC pthread_attr_t attr;
889 STATIC int attr_inited = 0;
890 STATIC int attr_joinable = PTHREAD_CREATE_JOINABLE;
fc04eb16
JH
891 if (! attr_inited) {
892 pthread_attr_init(&attr);
893 attr_inited = 1;
894 }
895
fa26028c 896# ifdef PTHREAD_ATTR_SETDETACHSTATE
fc04eb16
JH
897 /* Threads start out joinable */
898 PTHREAD_ATTR_SETDETACHSTATE(&attr, attr_joinable);
fa26028c 899# endif
fc04eb16 900
514612b7 901# ifdef _POSIX_THREAD_ATTR_STACKSIZE
fc04eb16 902 /* Set thread's stack size */
514612b7
JH
903 if (thread->stack_size > 0) {
904 rc_stack_size = pthread_attr_setstacksize(&attr, (size_t)thread->stack_size);
905 }
3eb37d38
AB
906# endif
907
fc04eb16
JH
908 /* Create the thread */
909 if (! rc_stack_size) {
910# ifdef OLD_PTHREADS_API
911 rc_thread_create = pthread_create(&thread->thr,
912 attr,
913 S_ithread_run,
914 (void *)thread);
915# else
916# if defined(HAS_PTHREAD_ATTR_SETSCOPE) && defined(PTHREAD_SCOPE_SYSTEM)
917 pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);
918# endif
919 rc_thread_create = pthread_create(&thread->thr,
920 &attr,
921 S_ithread_run,
922 (void *)thread);
19a077f6 923# endif
fc04eb16 924 }
514612b7 925
8264cf32 926#ifndef WIN32
b762d866
JW
927 /* Now it's safe to accept signals, since we're in our own interpreter's
928 * context and we have created the thread.
929 */
930 S_set_sigmask(&thread->initial_sigmask);
8264cf32 931#endif
b762d866 932
514612b7
JH
933# ifdef _POSIX_THREAD_ATTR_STACKSIZE
934 /* Try to get thread's actual stack size */
935 {
936 size_t stacksize;
58a3a76c
JH
937#ifdef HPUX1020
938 stacksize = pthread_attr_getstacksize(attr);
939#else
940 if (! pthread_attr_getstacksize(&attr, &stacksize))
941#endif
942 if (stacksize > 0) {
514612b7
JH
943 thread->stack_size = (IV)stacksize;
944 }
514612b7
JH
945 }
946# endif
fc04eb16 947 }
82c40bf6 948#endif
bcd9ca9b 949
fc04eb16 950 /* Check for errors */
d94006e8 951#ifdef WIN32
fc04eb16 952 if (thread->handle == NULL) {
d94006e8 953#else
fc04eb16 954 if (rc_stack_size || rc_thread_create) {
d94006e8 955#endif
9ca4d7fd 956 /* Must unlock mutex for destruct call */
5c6ff896 957 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
adc09a0e 958 thread->state |= PERL_ITHR_NONVIABLE;
6ebc233e 959 S_ithread_free(aTHX_ thread); /* Releases MUTEX */
d94006e8 960#ifndef WIN32
514612b7 961 if (ckWARN_d(WARN_THREADS)) {
fea7688c 962 if (rc_stack_size) {
514612b7 963 Perl_warn(aTHX_ "Thread creation failed: pthread_attr_setstacksize(%" IVdf ") returned %d", thread->stack_size, rc_stack_size);
fea7688c 964 } else {
514612b7 965 Perl_warn(aTHX_ "Thread creation failed: pthread_create returned %d", rc_thread_create);
fea7688c 966 }
514612b7 967 }
d94006e8 968#endif
9ca4d7fd 969 return (NULL);
fc04eb16
JH
970 }
971
5c6ff896 972 MY_POOL.running_threads++;
9ca4d7fd 973 return (thread);
68795e93 974}
47ba8780 975
73e09c8f 976#endif /* USE_ITHREADS */
e1c44605 977
fcea4b7c 978
fc04eb16 979MODULE = threads PACKAGE = threads PREFIX = ithread_
68795e93 980PROTOTYPES: DISABLE
8222d950 981
73e09c8f
JH
982#ifdef USE_ITHREADS
983
68795e93 984void
f4cc38af
JH
985ithread_create(...)
986 PREINIT:
987 char *classname;
514612b7 988 ithread *thread;
f4cc38af 989 SV *function_to_call;
514612b7
JH
990 HV *specs;
991 IV stack_size;
9d9ff5b1 992 int context;
69a9b4b8
RGS
993 int exit_opt;
994 SV *thread_exit_only;
9d9ff5b1 995 char *str;
514612b7 996 int idx;
5c6ff896 997 dMY_POOL;
f4cc38af 998 CODE:
514612b7 999 if ((items >= 2) && SvROK(ST(1)) && SvTYPE(SvRV(ST(1)))==SVt_PVHV) {
fea7688c 1000 if (--items < 2) {
18b9e6f5 1001 Perl_croak(aTHX_ "Usage: threads->create(\\%%specs, function, ...)");
fea7688c 1002 }
514612b7
JH
1003 specs = (HV*)SvRV(ST(1));
1004 idx = 1;
1005 } else {
fea7688c 1006 if (items < 2) {
514612b7 1007 Perl_croak(aTHX_ "Usage: threads->create(function, ...)");
fea7688c 1008 }
514612b7
JH
1009 specs = NULL;
1010 idx = 0;
1011 }
f4cc38af 1012
514612b7
JH
1013 if (sv_isobject(ST(0))) {
1014 /* $thr->create() */
1015 classname = HvNAME(SvSTASH(SvRV(ST(0))));
1016 thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
8718f9a1 1017 MUTEX_LOCK(&thread->mutex);
514612b7 1018 stack_size = thread->stack_size;
69a9b4b8 1019 exit_opt = thread->state & PERL_ITHR_THREAD_EXIT_ONLY;
8718f9a1 1020 MUTEX_UNLOCK(&thread->mutex);
514612b7
JH
1021 } else {
1022 /* threads->create() */
1023 classname = (char *)SvPV_nolen(ST(0));
5c6ff896 1024 stack_size = MY_POOL.default_stack_size;
8583b257 1025 thread_exit_only = get_sv("threads::thread_exit_only", GV_ADD);
69a9b4b8
RGS
1026 exit_opt = (SvTRUE(thread_exit_only))
1027 ? PERL_ITHR_THREAD_EXIT_ONLY : 0;
514612b7
JH
1028 }
1029
1030 function_to_call = ST(idx+1);
1031
9d9ff5b1 1032 context = -1;
514612b7 1033 if (specs) {
b1faab35 1034 SV **svp;
514612b7 1035 /* stack_size */
b1faab35
NC
1036 if ((svp = hv_fetch(specs, "stack", 5, 0))) {
1037 stack_size = SvIV(*svp);
1038 } else if ((svp = hv_fetch(specs, "stacksize", 9, 0))) {
1039 stack_size = SvIV(*svp);
1040 } else if ((svp = hv_fetch(specs, "stack_size", 10, 0))) {
1041 stack_size = SvIV(*svp);
514612b7 1042 }
9d9ff5b1
JH
1043
1044 /* context */
b1faab35
NC
1045 if ((svp = hv_fetch(specs, "context", 7, 0))) {
1046 str = (char *)SvPV_nolen(*svp);
9d9ff5b1
JH
1047 switch (*str) {
1048 case 'a':
1049 case 'A':
da140a40
JH
1050 case 'l':
1051 case 'L':
9d9ff5b1
JH
1052 context = G_ARRAY;
1053 break;
1054 case 's':
1055 case 'S':
1056 context = G_SCALAR;
1057 break;
1058 case 'v':
1059 case 'V':
1060 context = G_VOID;
1061 break;
1062 default:
1063 Perl_croak(aTHX_ "Invalid context: %s", str);
1064 }
b1faab35
NC
1065 } else if ((svp = hv_fetch(specs, "array", 5, 0))) {
1066 if (SvTRUE(*svp)) {
9d9ff5b1
JH
1067 context = G_ARRAY;
1068 }
b1faab35
NC
1069 } else if ((svp = hv_fetch(specs, "list", 4, 0))) {
1070 if (SvTRUE(*svp)) {
da140a40
JH
1071 context = G_ARRAY;
1072 }
b1faab35
NC
1073 } else if ((svp = hv_fetch(specs, "scalar", 6, 0))) {
1074 if (SvTRUE(*svp)) {
9d9ff5b1
JH
1075 context = G_SCALAR;
1076 }
b1faab35
NC
1077 } else if ((svp = hv_fetch(specs, "void", 4, 0))) {
1078 if (SvTRUE(*svp)) {
9d9ff5b1
JH
1079 context = G_VOID;
1080 }
1081 }
69a9b4b8
RGS
1082
1083 /* exit => thread_only */
b1faab35
NC
1084 if ((svp = hv_fetch(specs, "exit", 4, 0))) {
1085 str = (char *)SvPV_nolen(*svp);
69a9b4b8
RGS
1086 exit_opt = (*str == 't' || *str == 'T')
1087 ? PERL_ITHR_THREAD_EXIT_ONLY : 0;
1088 }
9d9ff5b1
JH
1089 }
1090 if (context == -1) {
1091 context = GIMME_V; /* Implicit context */
1092 } else {
1093 context |= (GIMME_V & (~(G_ARRAY|G_SCALAR|G_VOID)));
514612b7 1094 }
f4cc38af 1095
f4cc38af 1096 /* Create thread */
5c6ff896 1097 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
9ca4d7fd
JH
1098 thread = S_ithread_create(aTHX_ function_to_call,
1099 stack_size,
1100 context,
1101 exit_opt,
680818c0
NC
1102 ax + idx + 2,
1103 items > 2 ? items - 2 : 0);
9ca4d7fd
JH
1104 if (! thread) {
1105 XSRETURN_UNDEF; /* Mutex already unlocked */
1106 }
861d5cbe 1107 ST(0) = sv_2mortal(S_ithread_to_SV(aTHX_ Nullsv, thread, classname, FALSE));
adc09a0e 1108 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
9ca4d7fd
JH
1109
1110 /* Let thread run */
1111 MUTEX_UNLOCK(&thread->mutex);
9ca4d7fd 1112
f4cc38af
JH
1113 /* XSRETURN(1); - implied */
1114
8222d950 1115
68795e93 1116void
f4cc38af
JH
1117ithread_list(...)
1118 PREINIT:
1119 char *classname;
fc04eb16 1120 ithread *thread;
f4cc38af
JH
1121 int list_context;
1122 IV count = 0;
11db694d 1123 int want_running = 0;
8718f9a1 1124 int state;
5c6ff896 1125 dMY_POOL;
f4cc38af
JH
1126 PPCODE:
1127 /* Class method only */
fea7688c 1128 if (SvROK(ST(0))) {
ead32952 1129 Perl_croak(aTHX_ "Usage: threads->list(...)");
fea7688c 1130 }
f4cc38af
JH
1131 classname = (char *)SvPV_nolen(ST(0));
1132
1133 /* Calling context */
1134 list_context = (GIMME_V == G_ARRAY);
1135
ead32952
JH
1136 /* Running or joinable parameter */
1137 if (items > 1) {
1138 want_running = SvTRUE(ST(1));
1139 }
1140
f4cc38af 1141 /* Walk through threads list */
5c6ff896
JH
1142 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
1143 for (thread = MY_POOL.main_thread.next;
1144 thread != &MY_POOL.main_thread;
fc04eb16 1145 thread = thread->next)
f4cc38af 1146 {
8718f9a1
JH
1147 MUTEX_LOCK(&thread->mutex);
1148 state = thread->state;
1149 MUTEX_UNLOCK(&thread->mutex);
1150
f4cc38af 1151 /* Ignore detached or joined threads */
8718f9a1 1152 if (state & PERL_ITHR_UNCALLABLE) {
f4cc38af
JH
1153 continue;
1154 }
ead32952
JH
1155
1156 /* Filter per parameter */
1157 if (items > 1) {
1158 if (want_running) {
8718f9a1 1159 if (state & PERL_ITHR_FINISHED) {
ead32952
JH
1160 continue; /* Not running */
1161 }
1162 } else {
8718f9a1 1163 if (! (state & PERL_ITHR_FINISHED)) {
ead32952
JH
1164 continue; /* Still running - not joinable yet */
1165 }
1166 }
1167 }
1168
f4cc38af
JH
1169 /* Push object on stack if list context */
1170 if (list_context) {
861d5cbe 1171 XPUSHs(sv_2mortal(S_ithread_to_SV(aTHX_ Nullsv, thread, classname, TRUE)));
f4cc38af
JH
1172 }
1173 count++;
1174 }
5c6ff896 1175 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
f4cc38af
JH
1176 /* If scalar context, send back count */
1177 if (! list_context) {
1178 XSRETURN_IV(count);
1179 }
678a9b6c
AB
1180
1181
1182void
f4cc38af
JH
1183ithread_self(...)
1184 PREINIT:
1185 char *classname;
fcea4b7c 1186 ithread *thread;
f4cc38af
JH
1187 CODE:
1188 /* Class method only */
11db694d 1189 if ((items != 1) || SvROK(ST(0))) {
f4cc38af 1190 Perl_croak(aTHX_ "Usage: threads->self()");
fea7688c 1191 }
f4cc38af
JH
1192 classname = (char *)SvPV_nolen(ST(0));
1193
fcea4b7c
JH
1194 thread = S_ithread_get(aTHX);
1195
861d5cbe 1196 ST(0) = sv_2mortal(S_ithread_to_SV(aTHX_ Nullsv, thread, classname, TRUE));
f4cc38af 1197 /* XSRETURN(1); - implied */
47ba8780 1198
47ba8780
AB
1199
1200void
f4cc38af
JH
1201ithread_tid(...)
1202 PREINIT:
1203 ithread *thread;
1204 CODE:
11db694d 1205 PERL_UNUSED_VAR(items);
861d5cbe 1206 thread = S_SV_to_ithread(aTHX_ ST(0));
f4cc38af
JH
1207 XST_mUV(0, thread->tid);
1208 /* XSRETURN(1); - implied */
1209
e1c44605 1210
f9dff5f5 1211void
f4cc38af
JH
1212ithread_join(...)
1213 PREINIT:
fcea4b7c 1214 ithread *thread;
8718f9a1 1215 ithread *current_thread;
fcea4b7c 1216 int join_err;
6ebc233e 1217 AV *params = NULL;
f4cc38af
JH
1218 int len;
1219 int ii;
12701bb8 1220#ifndef WIN32
8718f9a1 1221 int rc_join;
fcea4b7c
JH
1222 void *retval;
1223#endif
5c6ff896 1224 dMY_POOL;
f4cc38af
JH
1225 PPCODE:
1226 /* Object method only */
11db694d 1227 if ((items != 1) || ! sv_isobject(ST(0))) {
f4cc38af 1228 Perl_croak(aTHX_ "Usage: $thr->join()");
fea7688c 1229 }
f4cc38af 1230
8718f9a1 1231 /* Check if the thread is joinable and not ourselves */
861d5cbe 1232 thread = S_SV_to_ithread(aTHX_ ST(0));
8718f9a1
JH
1233 current_thread = S_ithread_get(aTHX);
1234
1235 MUTEX_LOCK(&thread->mutex);
1236 if ((join_err = (thread->state & PERL_ITHR_UNCALLABLE))) {
1237 MUTEX_UNLOCK(&thread->mutex);
1238 Perl_croak(aTHX_ (join_err & PERL_ITHR_DETACHED)
1239 ? "Cannot join a detached thread"
1240 : "Thread already joined");
1241 } else if (thread->tid == current_thread->tid) {
1242 MUTEX_UNLOCK(&thread->mutex);
1243 Perl_croak(aTHX_ "Cannot join self");
fcea4b7c
JH
1244 }
1245
8718f9a1
JH
1246 /* Mark as joined */
1247 thread->state |= PERL_ITHR_JOINED;
1248 MUTEX_UNLOCK(&thread->mutex);
1249
1250 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
1251 MY_POOL.joinable_threads--;
1252 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
1253
fcea4b7c
JH
1254 /* Join the thread */
1255#ifdef WIN32
8718f9a1
JH
1256 if (WaitForSingleObject(thread->handle, INFINITE) != WAIT_OBJECT_0) {
1257 /* Timeout/abandonment unexpected here; check $^E */
1258 Perl_croak(aTHX_ "PANIC: underlying join failed");
1259 };
fcea4b7c 1260#else
8718f9a1
JH
1261 if ((rc_join = pthread_join(thread->thr, &retval)) != 0) {
1262 /* In progress/deadlock/unknown unexpected here; check $! */
1263 errno = rc_join;
1264 Perl_croak(aTHX_ "PANIC: underlying join failed");
1265 };
fcea4b7c
JH
1266#endif
1267
1268 MUTEX_LOCK(&thread->mutex);
fcea4b7c 1269 /* Get the return value from the call_sv */
955c272e 1270 /* Objects do not survive this process - FIXME */
7df0357e 1271 if ((thread->gimme & G_WANT) != G_VOID) {
dfa4c013
JH
1272#if (PERL_VERSION < 13) || (PERL_VERSION == 13 && PERL_SUBVERSION <= 1)
1273 AV *params_copy;
1274 PerlInterpreter *other_perl;
1275 CLONE_PARAMS clone_params;
1276
1277 params_copy = thread->params;
1278 other_perl = thread->interp;
1279 clone_params.stashes = newAV();
1280 clone_params.flags = CLONEf_JOIN_IN;
1281 PL_ptr_table = ptr_table_new();
1282 S_ithread_set(aTHX_ thread);
1283 /* Ensure 'meaningful' addresses retain their meaning */
1284 ptr_table_store(PL_ptr_table, &other_perl->Isv_undef, &PL_sv_undef);
1285 ptr_table_store(PL_ptr_table, &other_perl->Isv_no, &PL_sv_no);
1286 ptr_table_store(PL_ptr_table, &other_perl->Isv_yes, &PL_sv_yes);
1287 params = (AV *)sv_dup((SV*)params_copy, &clone_params);
1288 S_ithread_set(aTHX_ current_thread);
1289 SvREFCNT_dec(clone_params.stashes);
1290 SvREFCNT_inc_void(params);
1291 ptr_table_free(PL_ptr_table);
1292 PL_ptr_table = NULL;
1293#else
fcea4b7c 1294 AV *params_copy;
f7abe70b
NC
1295 PerlInterpreter *other_perl = thread->interp;
1296 CLONE_PARAMS *clone_params = Perl_clone_params_new(other_perl, aTHX);
fcea4b7c 1297
78b7eff2 1298 params_copy = thread->params;
f7abe70b 1299 clone_params->flags |= CLONEf_JOIN_IN;
fcea4b7c 1300 PL_ptr_table = ptr_table_new();
fcea4b7c
JH
1301 S_ithread_set(aTHX_ thread);
1302 /* Ensure 'meaningful' addresses retain their meaning */
1303 ptr_table_store(PL_ptr_table, &other_perl->Isv_undef, &PL_sv_undef);
1304 ptr_table_store(PL_ptr_table, &other_perl->Isv_no, &PL_sv_no);
1305 ptr_table_store(PL_ptr_table, &other_perl->Isv_yes, &PL_sv_yes);
f7abe70b 1306 params = (AV *)sv_dup((SV*)params_copy, clone_params);
fcea4b7c 1307 S_ithread_set(aTHX_ current_thread);
dfa4c013 1308 Perl_clone_params_del(clone_params);
d4315dd6 1309 SvREFCNT_inc_void(params);
fcea4b7c
JH
1310 ptr_table_free(PL_ptr_table);
1311 PL_ptr_table = NULL;
dfa4c013 1312#endif
fcea4b7c
JH
1313 }
1314
955c272e
JH
1315 /* If thread didn't die, then we can free its interpreter */
1316 if (! (thread->state & PERL_ITHR_DIED)) {
1317 S_ithread_clear(aTHX_ thread);
1318 }
6ebc233e 1319 S_ithread_free(aTHX_ thread); /* Releases MUTEX */
955c272e 1320
fcea4b7c 1321 /* If no return values, then just return */
f4cc38af
JH
1322 if (! params) {
1323 XSRETURN_UNDEF;
1324 }
1325
1326 /* Put return values on stack */
1327 len = (int)AvFILL(params);
1328 for (ii=0; ii <= len; ii++) {
1329 SV* param = av_shift(params);
1330 XPUSHs(sv_2mortal(param));
1331 }
1332
1333 /* Free return value array */
1334 SvREFCNT_dec(params);
1335
1336
1337void
1338ithread_yield(...)
1339 CODE:
11db694d 1340 PERL_UNUSED_VAR(items);
f4cc38af
JH
1341 YIELD;
1342
1343
1344void
1345ithread_detach(...)
1346 PREINIT:
1347 ithread *thread;
fcea4b7c 1348 int detach_err;
5c6ff896 1349 dMY_POOL;
f4cc38af 1350 CODE:
11db694d
JH
1351 PERL_UNUSED_VAR(items);
1352
fcea4b7c 1353 /* Detach the thread */
8718f9a1 1354 thread = S_SV_to_ithread(aTHX_ ST(0));
5c6ff896 1355 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
9ca4d7fd 1356 MUTEX_LOCK(&thread->mutex);
8718f9a1
JH
1357 if (! (detach_err = (thread->state & PERL_ITHR_UNCALLABLE))) {
1358 /* Thread is detachable */
1359 thread->state |= PERL_ITHR_DETACHED;
fcea4b7c 1360#ifdef WIN32
8718f9a1 1361 /* Windows has no 'detach thread' function */
fcea4b7c 1362#else
8718f9a1 1363 PERL_THREAD_DETACH(thread->thr);
fcea4b7c 1364#endif
8718f9a1
JH
1365 if (thread->state & PERL_ITHR_FINISHED) {
1366 MY_POOL.joinable_threads--;
1367 } else {
1368 MY_POOL.running_threads--;
1369 MY_POOL.detached_threads++;
1370 }
4dcb9e53 1371 }
adc09a0e 1372 MUTEX_UNLOCK(&thread->mutex);
5c6ff896 1373 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
4dcb9e53 1374
8718f9a1
JH
1375 if (detach_err) {
1376 Perl_croak(aTHX_ (detach_err & PERL_ITHR_DETACHED)
1377 ? "Thread already detached"
1378 : "Cannot detach a joined thread");
1379 }
1380
955c272e
JH
1381 /* If thread is finished and didn't die,
1382 * then we can free its interpreter */
1383 MUTEX_LOCK(&thread->mutex);
1384 if ((thread->state & PERL_ITHR_FINISHED) &&
1385 ! (thread->state & PERL_ITHR_DIED))
1386 {
1387 S_ithread_clear(aTHX_ thread);
1388 }
6ebc233e 1389 S_ithread_free(aTHX_ thread); /* Releases MUTEX */
f4cc38af 1390
47ba8780
AB
1391
1392void
c0003851
JH
1393ithread_kill(...)
1394 PREINIT:
1395 ithread *thread;
1396 char *sig_name;
1397 IV signal;
414fa04c 1398 int no_handler = 1;
c0003851
JH
1399 CODE:
1400 /* Must have safe signals */
fea7688c 1401 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG) {
4dcb9e53 1402 Perl_croak(aTHX_ "Cannot signal threads without safe signals");
fea7688c 1403 }
c0003851
JH
1404
1405 /* Object method only */
11db694d 1406 if ((items != 2) || ! sv_isobject(ST(0))) {
c0003851 1407 Perl_croak(aTHX_ "Usage: $thr->kill('SIG...')");
fea7688c 1408 }
c0003851 1409
c0003851
JH
1410 /* Get signal */
1411 sig_name = SvPV_nolen(ST(1));
1412 if (isALPHA(*sig_name)) {
fea7688c 1413 if (*sig_name == 'S' && sig_name[1] == 'I' && sig_name[2] == 'G') {
c0003851 1414 sig_name += 3;
fea7688c
JH
1415 }
1416 if ((signal = whichsig(sig_name)) < 0) {
c0003851 1417 Perl_croak(aTHX_ "Unrecognized signal name: %s", sig_name);
fea7688c
JH
1418 }
1419 } else {
c0003851 1420 signal = SvIV(ST(1));
fea7688c 1421 }
c0003851
JH
1422
1423 /* Set the signal for the thread */
861d5cbe 1424 thread = S_SV_to_ithread(aTHX_ ST(0));
4dcb9e53 1425 MUTEX_LOCK(&thread->mutex);
99f57afc 1426 if (thread->interp && ! (thread->state & PERL_ITHR_FINISHED)) {
c0003851 1427 dTHXa(thread->interp);
414fa04c
JH
1428 if (PL_psig_pend && PL_psig_ptr[signal]) {
1429 PL_psig_pend[signal]++;
1430 PL_sig_pending = 1;
1431 no_handler = 0;
1432 }
1433 } else {
99f57afc 1434 /* Ignore signal to terminated/finished thread */
414fa04c 1435 no_handler = 0;
c0003851 1436 }
4dcb9e53 1437 MUTEX_UNLOCK(&thread->mutex);
c0003851 1438
414fa04c
JH
1439 if (no_handler) {
1440 Perl_croak(aTHX_ "Signal %s received in thread %"UVuf", but no signal handler set.", sig_name, thread->tid);
1441 }
1442
c0003851
JH
1443 /* Return the thread to allow for method chaining */
1444 ST(0) = ST(0);
1445 /* XSRETURN(1); - implied */
1446
1447
1448void
f4cc38af
JH
1449ithread_DESTROY(...)
1450 CODE:
11db694d 1451 PERL_UNUSED_VAR(items);
fcea4b7c 1452 sv_unmagic(SvRV(ST(0)), PERL_MAGIC_shared_scalar);
f4cc38af
JH
1453
1454
1455void
1456ithread_equal(...)
fc04eb16
JH
1457 PREINIT:
1458 int are_equal = 0;
f4cc38af 1459 CODE:
11db694d
JH
1460 PERL_UNUSED_VAR(items);
1461
fc04eb16 1462 /* Compares TIDs to determine thread equality */
f4cc38af
JH
1463 if (sv_isobject(ST(0)) && sv_isobject(ST(1))) {
1464 ithread *thr1 = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1465 ithread *thr2 = INT2PTR(ithread *, SvIV(SvRV(ST(1))));
fc04eb16
JH
1466 are_equal = (thr1->tid == thr2->tid);
1467 }
1468 if (are_equal) {
1469 XST_mYES(0);
f4cc38af 1470 } else {
fc04eb16 1471 /* Return 0 on false for backward compatibility */
f4cc38af
JH
1472 XST_mIV(0, 0);
1473 }
1474 /* XSRETURN(1); - implied */
1475
47ba8780 1476
47ba8780 1477void
f4cc38af
JH
1478ithread_object(...)
1479 PREINIT:
1480 char *classname;
b91a79b9 1481 SV *arg;
f4cc38af 1482 UV tid;
fc04eb16 1483 ithread *thread;
8718f9a1 1484 int state;
9ca4d7fd 1485 int have_obj = 0;
5c6ff896 1486 dMY_POOL;
f4cc38af
JH
1487 CODE:
1488 /* Class method only */
fea7688c 1489 if (SvROK(ST(0))) {
f4cc38af 1490 Perl_croak(aTHX_ "Usage: threads->object($tid)");
fea7688c 1491 }
f4cc38af
JH
1492 classname = (char *)SvPV_nolen(ST(0));
1493
b91a79b9
SM
1494 /* Turn $tid from PVLV to SV if needed (bug #73330) */
1495 arg = ST(1);
1496 SvGETMAGIC(arg);
1497
1498 if ((items < 2) || ! SvOK(arg)) {
f4cc38af
JH
1499 XSRETURN_UNDEF;
1500 }
1501
fc04eb16 1502 /* threads->object($tid) */
b91a79b9 1503 tid = SvUV(arg);
f4cc38af 1504
b91a79b9
SM
1505 /* If current thread wants its own object, then behave the same as
1506 ->self() */
1507 thread = S_ithread_get(aTHX);
1508 if (thread->tid == tid) {
1509 ST(0) = sv_2mortal(S_ithread_to_SV(aTHX_ Nullsv, thread, classname, TRUE));
1510 have_obj = 1;
1511
1512 } else {
1513 /* Walk through threads list */
1514 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
1515 for (thread = MY_POOL.main_thread.next;
1516 thread != &MY_POOL.main_thread;
1517 thread = thread->next)
1518 {
1519 /* Look for TID */
1520 if (thread->tid == tid) {
1521 /* Ignore if detached or joined */
1522 MUTEX_LOCK(&thread->mutex);
1523 state = thread->state;
1524 MUTEX_UNLOCK(&thread->mutex);
1525 if (! (state & PERL_ITHR_UNCALLABLE)) {
1526 /* Put object on stack */
1527 ST(0) = sv_2mortal(S_ithread_to_SV(aTHX_ Nullsv, thread, classname, TRUE));
1528 have_obj = 1;
1529 }
1530 break;
9ca4d7fd 1531 }
f4cc38af 1532 }
b91a79b9 1533 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
f4cc38af 1534 }
9ca4d7fd
JH
1535
1536 if (! have_obj) {
f4cc38af
JH
1537 XSRETURN_UNDEF;
1538 }
1539 /* XSRETURN(1); - implied */
1540
1541
1542void
1543ithread__handle(...);
1544 PREINIT:
1545 ithread *thread;
1546 CODE:
11db694d 1547 PERL_UNUSED_VAR(items);
861d5cbe 1548 thread = S_SV_to_ithread(aTHX_ ST(0));
f4cc38af 1549#ifdef WIN32
fcea4b7c 1550 XST_mUV(0, PTR2UV(&thread->handle));
f4cc38af 1551#else
75ba4ae2 1552 XST_mUV(0, PTR2UV(&thread->thr));
f4cc38af
JH
1553#endif
1554 /* XSRETURN(1); - implied */
68795e93 1555
514612b7
JH
1556
1557void
1558ithread_get_stack_size(...)
1559 PREINIT:
1560 IV stack_size;
5c6ff896 1561 dMY_POOL;
514612b7 1562 CODE:
11db694d 1563 PERL_UNUSED_VAR(items);
514612b7
JH
1564 if (sv_isobject(ST(0))) {
1565 /* $thr->get_stack_size() */
1566 ithread *thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1567 stack_size = thread->stack_size;
1568 } else {
1569 /* threads->get_stack_size() */
5c6ff896 1570 stack_size = MY_POOL.default_stack_size;
514612b7
JH
1571 }
1572 XST_mIV(0, stack_size);
1573 /* XSRETURN(1); - implied */
1574
1575
1576void
1577ithread_set_stack_size(...)
1578 PREINIT:
1579 IV old_size;
5c6ff896 1580 dMY_POOL;
514612b7 1581 CODE:
fea7688c 1582 if (items != 2) {
514612b7 1583 Perl_croak(aTHX_ "Usage: threads->set_stack_size($size)");
fea7688c
JH
1584 }
1585 if (sv_isobject(ST(0))) {
514612b7 1586 Perl_croak(aTHX_ "Cannot change stack size of an existing thread");
fea7688c 1587 }
6ebc233e
RGS
1588 if (! looks_like_number(ST(1))) {
1589 Perl_croak(aTHX_ "Stack size must be numeric");
1590 }
514612b7 1591
5c6ff896
JH
1592 old_size = MY_POOL.default_stack_size;
1593 MY_POOL.default_stack_size = S_good_stack_size(aTHX_ SvIV(ST(1)));
514612b7
JH
1594 XST_mIV(0, old_size);
1595 /* XSRETURN(1); - implied */
1596
ead32952
JH
1597
1598void
1599ithread_is_running(...)
1600 PREINIT:
1601 ithread *thread;
1602 CODE:
1603 /* Object method only */
11db694d 1604 if ((items != 1) || ! sv_isobject(ST(0))) {
ead32952 1605 Perl_croak(aTHX_ "Usage: $thr->is_running()");
fea7688c 1606 }
ead32952
JH
1607
1608 thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
8718f9a1 1609 MUTEX_LOCK(&thread->mutex);
ead32952 1610 ST(0) = (thread->state & PERL_ITHR_FINISHED) ? &PL_sv_no : &PL_sv_yes;
8718f9a1 1611 MUTEX_UNLOCK(&thread->mutex);
ead32952
JH
1612 /* XSRETURN(1); - implied */
1613
1614
1615void
1616ithread_is_detached(...)
1617 PREINIT:
1618 ithread *thread;
1619 CODE:
11db694d 1620 PERL_UNUSED_VAR(items);
861d5cbe 1621 thread = S_SV_to_ithread(aTHX_ ST(0));
8718f9a1 1622 MUTEX_LOCK(&thread->mutex);
ead32952 1623 ST(0) = (thread->state & PERL_ITHR_DETACHED) ? &PL_sv_yes : &PL_sv_no;
8718f9a1 1624 MUTEX_UNLOCK(&thread->mutex);
ead32952
JH
1625 /* XSRETURN(1); - implied */
1626
1627
1628void
1629ithread_is_joinable(...)
1630 PREINIT:
1631 ithread *thread;
1632 CODE:
1633 /* Object method only */
11db694d 1634 if ((items != 1) || ! sv_isobject(ST(0))) {
ead32952 1635 Perl_croak(aTHX_ "Usage: $thr->is_joinable()");
fea7688c 1636 }
ead32952
JH
1637
1638 thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1639 MUTEX_LOCK(&thread->mutex);
1640 ST(0) = ((thread->state & PERL_ITHR_FINISHED) &&
8718f9a1 1641 ! (thread->state & PERL_ITHR_UNCALLABLE))
ead32952
JH
1642 ? &PL_sv_yes : &PL_sv_no;
1643 MUTEX_UNLOCK(&thread->mutex);
1644 /* XSRETURN(1); - implied */
1645
1646
1647void
1648ithread_wantarray(...)
1649 PREINIT:
1650 ithread *thread;
1651 CODE:
11db694d 1652 PERL_UNUSED_VAR(items);
861d5cbe 1653 thread = S_SV_to_ithread(aTHX_ ST(0));
7df0357e
NC
1654 ST(0) = ((thread->gimme & G_WANT) == G_ARRAY) ? &PL_sv_yes :
1655 ((thread->gimme & G_WANT) == G_VOID) ? &PL_sv_undef
7ef93cb2 1656 /* G_SCALAR */ : &PL_sv_no;
ead32952
JH
1657 /* XSRETURN(1); - implied */
1658
69a9b4b8
RGS
1659
1660void
1661ithread_set_thread_exit_only(...)
1662 PREINIT:
1663 ithread *thread;
1664 CODE:
fea7688c 1665 if (items != 2) {
69a9b4b8 1666 Perl_croak(aTHX_ "Usage: ->set_thread_exit_only(boolean)");
fea7688c 1667 }
861d5cbe 1668 thread = S_SV_to_ithread(aTHX_ ST(0));
69a9b4b8
RGS
1669 MUTEX_LOCK(&thread->mutex);
1670 if (SvTRUE(ST(1))) {
1671 thread->state |= PERL_ITHR_THREAD_EXIT_ONLY;
1672 } else {
1673 thread->state &= ~PERL_ITHR_THREAD_EXIT_ONLY;
1674 }
1675 MUTEX_UNLOCK(&thread->mutex);
1676
955c272e
JH
1677
1678void
1679ithread_error(...)
1680 PREINIT:
1681 ithread *thread;
1682 SV *err = NULL;
1683 CODE:
1684 /* Object method only */
1685 if ((items != 1) || ! sv_isobject(ST(0))) {
1686 Perl_croak(aTHX_ "Usage: $thr->err()");
1687 }
1688
1689 thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1690 MUTEX_LOCK(&thread->mutex);
1691
1692 /* If thread died, then clone the error into the calling thread */
1693 if (thread->state & PERL_ITHR_DIED) {
dfa4c013
JH
1694#if (PERL_VERSION < 13) || (PERL_VERSION == 13 && PERL_SUBVERSION <= 1)
1695 PerlInterpreter *other_perl;
1696 CLONE_PARAMS clone_params;
1697 ithread *current_thread;
1698
1699 other_perl = thread->interp;
1700 clone_params.stashes = newAV();
1701 clone_params.flags = CLONEf_JOIN_IN;
1702 PL_ptr_table = ptr_table_new();
1703 current_thread = S_ithread_get(aTHX);
1704 S_ithread_set(aTHX_ thread);
1705 /* Ensure 'meaningful' addresses retain their meaning */
1706 ptr_table_store(PL_ptr_table, &other_perl->Isv_undef, &PL_sv_undef);
1707 ptr_table_store(PL_ptr_table, &other_perl->Isv_no, &PL_sv_no);
1708 ptr_table_store(PL_ptr_table, &other_perl->Isv_yes, &PL_sv_yes);
1709 err = sv_dup(thread->err, &clone_params);
1710 S_ithread_set(aTHX_ current_thread);
1711 SvREFCNT_dec(clone_params.stashes);
1712 SvREFCNT_inc_void(err);
1713 /* If error was an object, bless it into the correct class */
1714 if (thread->err_class) {
1715 sv_bless(err, gv_stashpv(thread->err_class, 1));
1716 }
1717 ptr_table_free(PL_ptr_table);
1718 PL_ptr_table = NULL;
1719#else
f7abe70b
NC
1720 PerlInterpreter *other_perl = thread->interp;
1721 CLONE_PARAMS *clone_params = Perl_clone_params_new(other_perl, aTHX);
955c272e
JH
1722 ithread *current_thread;
1723
f7abe70b 1724 clone_params->flags |= CLONEf_JOIN_IN;
955c272e
JH
1725 PL_ptr_table = ptr_table_new();
1726 current_thread = S_ithread_get(aTHX);
1727 S_ithread_set(aTHX_ thread);
1728 /* Ensure 'meaningful' addresses retain their meaning */
1729 ptr_table_store(PL_ptr_table, &other_perl->Isv_undef, &PL_sv_undef);
1730 ptr_table_store(PL_ptr_table, &other_perl->Isv_no, &PL_sv_no);
1731 ptr_table_store(PL_ptr_table, &other_perl->Isv_yes, &PL_sv_yes);
f7abe70b 1732 err = sv_dup(thread->err, clone_params);
955c272e 1733 S_ithread_set(aTHX_ current_thread);
dfa4c013 1734 Perl_clone_params_del(clone_params);
955c272e
JH
1735 SvREFCNT_inc_void(err);
1736 /* If error was an object, bless it into the correct class */
1737 if (thread->err_class) {
1738 sv_bless(err, gv_stashpv(thread->err_class, 1));
1739 }
1740 ptr_table_free(PL_ptr_table);
1741 PL_ptr_table = NULL;
dfa4c013 1742#endif
955c272e
JH
1743 }
1744
1745 MUTEX_UNLOCK(&thread->mutex);
1746
1747 if (! err) {
1748 XSRETURN_UNDEF;
1749 }
1750
1751 ST(0) = sv_2mortal(err);
1752 /* XSRETURN(1); - implied */
1753
1754
73e09c8f
JH
1755#endif /* USE_ITHREADS */
1756
fc04eb16 1757
68795e93
NIS
1758BOOT:
1759{
73e09c8f 1760#ifdef USE_ITHREADS
5c6ff896
JH
1761 SV *my_pool_sv = *hv_fetch(PL_modglobal, MY_POOL_KEY,
1762 sizeof(MY_POOL_KEY)-1, TRUE);
1763 my_pool_t *my_poolp = (my_pool_t*)SvPVX(newSV(sizeof(my_pool_t)-1));
1764
fc04eb16
JH
1765 MY_CXT_INIT;
1766
5c6ff896
JH
1767 Zero(my_poolp, 1, my_pool_t);
1768 sv_setuv(my_pool_sv, PTR2UV(my_poolp));
1769
fc04eb16 1770 PL_perl_destruct_level = 2;
5c6ff896
JH
1771 MUTEX_INIT(&MY_POOL.create_destruct_mutex);
1772 MUTEX_LOCK(&MY_POOL.create_destruct_mutex);
fc04eb16
JH
1773
1774 PL_threadhook = &Perl_ithread_hook;
1775
5c6ff896
JH
1776 MY_POOL.tid_counter = 1;
1777# ifdef THREAD_CREATE_NEEDS_STACK
1778 MY_POOL.default_stack_size = THREAD_CREATE_NEEDS_STACK;
1779# endif
1780
c372d929
JH
1781 /* The 'main' thread is thread 0.
1782 * It is detached (unjoinable) and immortal.
1783 */
fc04eb16 1784
5c6ff896 1785 MUTEX_INIT(&MY_POOL.main_thread.mutex);
fc04eb16
JH
1786
1787 /* Head of the threads list */
5c6ff896
JH
1788 MY_POOL.main_thread.next = &MY_POOL.main_thread;
1789 MY_POOL.main_thread.prev = &MY_POOL.main_thread;
fc04eb16 1790
5c6ff896 1791 MY_POOL.main_thread.count = 1; /* Immortal */
fc04eb16 1792
5c6ff896
JH
1793 MY_POOL.main_thread.interp = aTHX;
1794 MY_POOL.main_thread.state = PERL_ITHR_DETACHED; /* Detached */
1795 MY_POOL.main_thread.stack_size = MY_POOL.default_stack_size;
fc04eb16 1796# ifdef WIN32
5c6ff896 1797 MY_POOL.main_thread.thr = GetCurrentThreadId();
fc04eb16 1798# else
5c6ff896 1799 MY_POOL.main_thread.thr = pthread_self();
fc04eb16
JH
1800# endif
1801
5c6ff896
JH
1802 S_ithread_set(aTHX_ &MY_POOL.main_thread);
1803 MUTEX_UNLOCK(&MY_POOL.create_destruct_mutex);
73e09c8f 1804#endif /* USE_ITHREADS */
68795e93 1805}