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