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