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