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