threads 1.32
[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"
0f1612a7 5#ifdef HAS_PPPORT_H
404aaa48 6# define NEED_PL_signals
0f1612a7 7# define NEED_newRV_noinc
8# define NEED_sv_2pv_nolen
9# include "ppport.h"
10# include "threads.h"
11#endif
68795e93 12
73e09c8f 13#ifdef USE_ITHREADS
14
68795e93 15#ifdef WIN32
fc04eb16 16# include <windows.h>
514612b7 17 /* Supposed to be in Winbase.h */
18# ifndef STACK_SIZE_PARAM_IS_A_RESERVATION
19# define STACK_SIZE_PARAM_IS_A_RESERVATION 0x00010000
20# endif
fc04eb16 21# include <win32thread.h>
68795e93 22#else
fc04eb16 23# ifdef OS2
5c728af0 24typedef perl_os_thread pthread_t;
fc04eb16 25# else
26# include <pthread.h>
27# endif
28# include <thread.h>
29# define PERL_THREAD_SETSPECIFIC(k,v) pthread_setspecific(k,v)
30# ifdef OLD_PTHREADS_API
31# define PERL_THREAD_DETACH(t) pthread_detach(&(t))
32# else
33# define PERL_THREAD_DETACH(t) pthread_detach((t))
34# endif
467f3f08 35#endif
d305c2c9 36#if !defined(HAS_GETPAGESIZE) && defined(I_SYS_PARAM)
37# include <sys/param.h>
38#endif
68795e93 39
62375a60 40/* Values for 'state' member */
fc04eb16 41#define PERL_ITHR_JOINABLE 0
42#define PERL_ITHR_DETACHED 1
43#define PERL_ITHR_JOINED 2
44#define PERL_ITHR_FINISHED 4
45
46typedef struct _ithread {
47 struct _ithread *next; /* Next thread in the list */
48 struct _ithread *prev; /* Prev thread in the list */
49 PerlInterpreter *interp; /* The threads interpreter */
50 UV tid; /* Threads module's thread id */
51 perl_mutex mutex; /* Mutex for updating things in this struct */
9feacc09 52 int count; /* How many SVs have a reference to us */
fc04eb16 53 int state; /* Detached, joined, finished, etc. */
54 int gimme; /* Context of create */
55 SV *init_function; /* Code to run */
56 SV *params; /* Args to pass function */
68795e93 57#ifdef WIN32
fc04eb16 58 DWORD thr; /* OS's idea if thread id */
59 HANDLE handle; /* OS's waitable handle */
68795e93 60#else
fc04eb16 61 pthread_t thr; /* OS's handle for the thread */
68795e93 62#endif
514612b7 63 IV stack_size;
68795e93 64} ithread;
65
fc04eb16 66
67/* Used by Perl interpreter for thread context switching */
628ab322 68#define MY_CXT_KEY "threads::_guts" XS_VERSION
69
70typedef struct {
71 ithread *thread;
72} my_cxt_t;
73
74START_MY_CXT
75
76
fc04eb16 77/* Linked list of all threads */
f4cc38af 78static ithread *threads;
68795e93 79
fc04eb16 80/* Protects the creation and destruction of threads*/
81static perl_mutex create_destruct_mutex;
68795e93 82
f4cc38af 83static UV tid_counter = 0;
f4cc38af 84static IV active_threads = 0;
514612b7 85#ifdef THREAD_CREATE_NEEDS_STACK
86static IV default_stack_size = THREAD_CREATE_NEEDS_STACK;
87#else
88static IV default_stack_size = 0;
89#endif
90static IV page_size = 0;
c05ae023 91
92
fc04eb16 93/* Used by Perl interpreter for thread context switching */
f4cc38af 94static void
fc04eb16 95S_ithread_set(pTHX_ ithread *thread)
c05ae023 96{
628ab322 97 dMY_CXT;
98 MY_CXT.thread = thread;
c05ae023 99}
100
fc04eb16 101static ithread *
102S_ithread_get(pTHX)
103{
628ab322 104 dMY_CXT;
fc04eb16 105 return (MY_CXT.thread);
c05ae023 106}
107
108
fc04eb16 109/* Free any data (such as the Perl interpreter) attached to an ithread
110 * structure. This is a bit like undef on SVs, where the SV isn't freed,
111 * but the PVX is. Must be called with thread->mutex already held.
2e676467 112 */
2e676467 113static void
fc04eb16 114S_ithread_clear(pTHX_ ithread *thread)
2e676467 115{
116 PerlInterpreter *interp;
fc04eb16 117
2e676467 118 assert(thread->state & PERL_ITHR_FINISHED &&
f2cba68d 119 thread->state & (PERL_ITHR_DETACHED|PERL_ITHR_JOINED));
2e676467 120
121 interp = thread->interp;
122 if (interp) {
fc04eb16 123 dTHXa(interp);
124
125 PERL_SET_CONTEXT(interp);
126 S_ithread_set(aTHX_ thread);
f2cba68d 127
fc04eb16 128 SvREFCNT_dec(thread->params);
129 thread->params = Nullsv;
2e676467 130
fc04eb16 131 perl_destruct(interp);
132 thread->interp = NULL;
2e676467 133 }
134 if (interp)
fc04eb16 135 perl_free(interp);
136
2e676467 137 PERL_SET_CONTEXT(aTHX);
138}
139
68795e93 140
fc04eb16 141/* Free an ithread structure and any attached data if its count == 0 */
bcd9ca9b 142static void
fc04eb16 143S_ithread_destruct(pTHX_ ithread *thread)
68795e93 144{
385d56e4 145#ifdef WIN32
fc04eb16 146 HANDLE handle;
385d56e4 147#endif
148
fc04eb16 149 MUTEX_LOCK(&thread->mutex);
bcd9ca9b 150
fc04eb16 151 /* Thread is still in use */
152 if (thread->count != 0) {
153 MUTEX_UNLOCK(&thread->mutex);
154 return;
155 }
9feacc09 156
fc04eb16 157 MUTEX_LOCK(&create_destruct_mutex);
158 /* Main thread (0) is immortal and should never get here */
159 assert(thread->tid != 0);
160
161 /* Remove from circular list of threads */
162 thread->next->prev = thread->prev;
163 thread->prev->next = thread->next;
164 thread->next = NULL;
165 thread->prev = NULL;
166 MUTEX_UNLOCK(&create_destruct_mutex);
c2f2a82b 167
fc04eb16 168 /* Thread is now disowned */
169 S_ithread_clear(aTHX_ thread);
385d56e4 170
171#ifdef WIN32
fc04eb16 172 handle = thread->handle;
173 thread->handle = NULL;
385d56e4 174#endif
fc04eb16 175 MUTEX_UNLOCK(&thread->mutex);
176 MUTEX_DESTROY(&thread->mutex);
385d56e4 177
c7667023 178#ifdef WIN32
fc04eb16 179 if (handle)
180 CloseHandle(handle);
c7667023 181#endif
385d56e4 182
fc04eb16 183 /* Call PerlMemShared_free() in the context of the "first" interpreter
184 * per http://www.nntp.perl.org/group/perl.perl5.porters/110772
185 */
186 aTHX = PL_curinterp;
187 PerlMemShared_free(thread);
68795e93 188}
189
fc04eb16 190
191/* Called on exit */
62375a60 192int
193Perl_ithread_hook(pTHX)
194{
195 int veto_cleanup = 0;
196 MUTEX_LOCK(&create_destruct_mutex);
fc04eb16 197 if ((aTHX == PL_curinterp) && (active_threads != 1)) {
198 if (ckWARN_d(WARN_THREADS)) {
199 Perl_warn(aTHX_ "A thread exited while %" IVdf " threads were running", active_threads);
200 }
201 veto_cleanup = 1;
62375a60 202 }
203 MUTEX_UNLOCK(&create_destruct_mutex);
fc04eb16 204 return (veto_cleanup);
62375a60 205}
206
68795e93 207
208/* MAGIC (in mg.h sense) hooks */
209
210int
211ithread_mg_get(pTHX_ SV *sv, MAGIC *mg)
212{
fc04eb16 213 ithread *thread = (ithread *)mg->mg_ptr;
45977657 214 SvIV_set(sv, PTR2IV(thread));
68795e93 215 SvIOK_on(sv);
fc04eb16 216 return (0);
68795e93 217}
218
219int
220ithread_mg_free(pTHX_ SV *sv, MAGIC *mg)
221{
f2cba68d 222 ithread *thread = (ithread *)mg->mg_ptr;
223 int cleanup;
224
68795e93 225 MUTEX_LOCK(&thread->mutex);
f2cba68d 226 cleanup = ((--thread->count == 0) &&
227 (thread->state & PERL_ITHR_FINISHED) &&
228 (thread->state & (PERL_ITHR_DETACHED|PERL_ITHR_JOINED)));
229 MUTEX_UNLOCK(&thread->mutex);
230
231 if (cleanup)
232 S_ithread_destruct(aTHX_ thread);
fc04eb16 233 return (0);
68795e93 234}
235
236int
237ithread_mg_dup(pTHX_ MAGIC *mg, CLONE_PARAMS *param)
238{
fc04eb16 239 ithread *thread = (ithread *)mg->mg_ptr;
68795e93 240 MUTEX_LOCK(&thread->mutex);
68795e93 241 thread->count++;
242 MUTEX_UNLOCK(&thread->mutex);
fc04eb16 243 return (0);
68795e93 244}
245
246MGVTBL ithread_vtbl = {
fc04eb16 247 ithread_mg_get, /* get */
248 0, /* set */
249 0, /* len */
250 0, /* clear */
251 ithread_mg_free, /* free */
252 0, /* copy */
253 ithread_mg_dup /* dup */
68795e93 254};
255
47ba8780 256
514612b7 257/* Provided default, minimum and rational stack sizes */
258static IV
259good_stack_size(pTHX_ IV stack_size)
260{
261 /* Use default stack size if no stack size specified */
262 if (! stack_size)
263 return (default_stack_size);
264
265#ifdef PTHREAD_STACK_MIN
266 /* Can't use less than minimum */
267 if (stack_size < PTHREAD_STACK_MIN) {
268 if (ckWARN_d(WARN_THREADS)) {
269 Perl_warn(aTHX_ "Using minimum thread stack size of %" IVdf, (IV)PTHREAD_STACK_MIN);
270 }
271 return (PTHREAD_STACK_MIN);
272 }
273#endif
274
275 /* Round up to page size boundary */
276 if (page_size <= 0) {
d305c2c9 277#if defined(HAS_SYSCONF) && (defined(_SC_PAGESIZE) || defined(_SC_MMAP_PAGE_SIZE))
514612b7 278 SETERRNO(0, SS_NORMAL);
d305c2c9 279# ifdef _SC_PAGESIZE
514612b7 280 page_size = sysconf(_SC_PAGESIZE);
d305c2c9 281# else
514612b7 282 page_size = sysconf(_SC_MMAP_PAGE_SIZE);
d305c2c9 283# endif
514612b7 284 if ((long)page_size < 0) {
285 if (errno) {
286 SV * const error = get_sv("@", FALSE);
287 (void)SvUPGRADE(error, SVt_PV);
288 Perl_croak(aTHX_ "PANIC: sysconf: %s", SvPV_nolen(error));
289 } else {
290 Perl_croak(aTHX_ "PANIC: sysconf: pagesize unknown");
291 }
292 }
d305c2c9 293#else
294# ifdef HAS_GETPAGESIZE
514612b7 295 page_size = getpagesize();
514612b7 296# else
d305c2c9 297# if defined(I_SYS_PARAM) && defined(PAGESIZE)
298 page_size = PAGESIZE;
299# else
514612b7 300 page_size = 8192; /* A conservative default */
d305c2c9 301# endif
514612b7 302# endif
d305c2c9 303 if (page_size <= 0)
304 Perl_croak(aTHX_ "PANIC: bad pagesize %" IVdf, (IV)page_size);
514612b7 305#endif
306 }
307 stack_size = ((stack_size + (page_size - 1)) / page_size) * page_size;
308
309 return (stack_size);
310}
311
312
fc04eb16 313/* Starts executing the thread.
314 * Passed as the C level function to run in the new thread.
b1edfb69 315 */
47ba8780 316#ifdef WIN32
f4cc38af 317static THREAD_RET_TYPE
fc04eb16 318S_ithread_run(LPVOID arg)
47ba8780 319#else
fc04eb16 320static void *
321S_ithread_run(void * arg)
47ba8780 322#endif
fc04eb16 323{
324 ithread *thread = (ithread *)arg;
325 int cleanup;
f2cba68d 326
fc04eb16 327 dTHXa(thread->interp);
328 PERL_SET_CONTEXT(thread->interp);
329 S_ithread_set(aTHX_ thread);
47ba8780 330
68795e93 331#if 0
fc04eb16 332 /* Far from clear messing with ->thr child-side is a good idea */
333 MUTEX_LOCK(&thread->mutex);
47ba8780 334#ifdef WIN32
fc04eb16 335 thread->thr = GetCurrentThreadId();
47ba8780 336#else
fc04eb16 337 thread->thr = pthread_self();
47ba8780 338#endif
fc04eb16 339 MUTEX_UNLOCK(&thread->mutex);
68795e93 340#endif
47ba8780 341
fc04eb16 342 PL_perl_destruct_level = 2;
f2cba68d 343
fc04eb16 344 {
345 AV *params = (AV *)SvRV(thread->params);
346 int len = (int)av_len(params)+1;
347 int ii;
348
349 dSP;
350 ENTER;
351 SAVETMPS;
352
353 /* Put args on the stack */
354 PUSHMARK(SP);
355 for (ii=0; ii < len; ii++) {
356 XPUSHs(av_shift(params));
357 }
358 PUTBACK;
359
360 /* Run the specified function */
361 len = (int)call_sv(thread->init_function, thread->gimme|G_EVAL);
362
363 /* Remove args from stack and put back in params array */
364 SPAGAIN;
365 for (ii=len-1; ii >= 0; ii--) {
366 SV *sv = POPs;
367 av_store(params, ii, SvREFCNT_inc(sv));
368 }
369
370 /* Check for failure */
371 if (SvTRUE(ERRSV) && ckWARN_d(WARN_THREADS)) {
c0003851 372 Perl_warn(aTHX_ "Thread %" UVuf " terminated abnormally: %" SVf, thread->tid, ERRSV);
fc04eb16 373 }
374
375 FREETMPS;
376 LEAVE;
377
378 /* Release function ref */
379 SvREFCNT_dec(thread->init_function);
380 thread->init_function = Nullsv;
381 }
62375a60 382
fc04eb16 383 PerlIO_flush((PerlIO *)NULL);
384
385 MUTEX_LOCK(&thread->mutex);
386 /* Mark as finished */
387 thread->state |= PERL_ITHR_FINISHED;
388 /* Cleanup if detached */
389 cleanup = (thread->state & PERL_ITHR_DETACHED);
390 MUTEX_UNLOCK(&thread->mutex);
391
392 if (cleanup)
393 S_ithread_destruct(aTHX_ thread);
394
395 MUTEX_LOCK(&create_destruct_mutex);
396 active_threads--;
397 MUTEX_UNLOCK(&create_destruct_mutex);
91604d21 398
47ba8780 399#ifdef WIN32
fc04eb16 400 return ((DWORD)0);
e8f2bb9a 401#else
fc04eb16 402 return (0);
47ba8780 403#endif
68795e93 404}
405
fc04eb16 406
407/* Type conversion helper functions */
f4cc38af 408static SV *
68795e93 409ithread_to_SV(pTHX_ SV *obj, ithread *thread, char *classname, bool inc)
410{
411 SV *sv;
412 MAGIC *mg;
fc04eb16 413
68795e93 414 if (inc) {
fc04eb16 415 MUTEX_LOCK(&thread->mutex);
416 thread->count++;
417 MUTEX_UNLOCK(&thread->mutex);
418 }
419
420 if (! obj) {
421 obj = newSV(0);
68795e93 422 }
fc04eb16 423
424 sv = newSVrv(obj, classname);
425 sv_setiv(sv, PTR2IV(thread));
426 mg = sv_magicext(sv, Nullsv, PERL_MAGIC_shared_scalar, &ithread_vtbl, (char *)thread, 0);
68795e93 427 mg->mg_flags |= MGf_DUP;
428 SvREADONLY_on(sv);
fc04eb16 429
430 return (obj);
68795e93 431}
47ba8780 432
f4cc38af 433static ithread *
68795e93 434SV_to_ithread(pTHX_ SV *sv)
435{
fc04eb16 436 /* Argument is a thread */
437 if (SvROK(sv)) {
438 return (INT2PTR(ithread *, SvIV(SvRV(sv))));
439 }
440 /* Argument is classname, therefore return current thread */
441 return (S_ithread_get(aTHX));
47ba8780 442}
443
47ba8780 444
fc04eb16 445/* threads->create()
446 * Called in context of parent thread.
447 */
f4cc38af 448static SV *
fc04eb16 449S_ithread_create(
450 pTHX_ SV *obj,
451 char *classname,
452 SV *init_function,
514612b7 453 IV stack_size,
9d9ff5b1 454 int gimme,
fc04eb16 455 SV *params)
68795e93 456{
fc04eb16 457 ithread *thread;
458 CLONE_PARAMS clone_param;
459 ithread *current_thread = S_ithread_get(aTHX);
3b1c3273 460
fc04eb16 461 SV **tmps_tmp = PL_tmps_stack;
462 IV tmps_ix = PL_tmps_ix;
d94006e8 463#ifndef WIN32
fc04eb16 464 int rc_stack_size = 0;
465 int rc_thread_create = 0;
d94006e8 466#endif
3b1c3273 467
fc04eb16 468 MUTEX_LOCK(&create_destruct_mutex);
469
470 /* Allocate thread structure */
471 thread = (ithread *)PerlMemShared_malloc(sizeof(ithread));
472 if (!thread) {
473 MUTEX_UNLOCK(&create_destruct_mutex);
474 PerlLIO_write(PerlIO_fileno(Perl_error_log), PL_no_mem, strlen(PL_no_mem));
475 my_exit(1);
476 }
477 Zero(thread, 1, ithread);
478
479 /* Add to threads list */
480 thread->next = threads;
481 thread->prev = threads->prev;
482 threads->prev = thread;
483 thread->prev->next = thread;
c05ae023 484
fc04eb16 485 /* Set count to 1 immediately in case thread exits before
486 * we return to caller!
487 */
488 thread->count = 1;
489
490 MUTEX_INIT(&thread->mutex);
491 thread->tid = tid_counter++;
514612b7 492 thread->stack_size = good_stack_size(aTHX_ stack_size);
9d9ff5b1 493 thread->gimme = gimme;
fc04eb16 494
495 /* "Clone" our interpreter into the thread's interpreter.
496 * This gives thread access to "static data" and code.
497 */
498 PerlIO_flush((PerlIO *)NULL);
499 S_ithread_set(aTHX_ thread);
500
501 SAVEBOOL(PL_srand_called); /* Save this so it becomes the correct value */
502 PL_srand_called = FALSE; /* Set it to false so we can detect if it gets
503 set during the clone */
3b1c3273 504
47ba8780 505#ifdef WIN32
fc04eb16 506 thread->interp = perl_clone(aTHX, CLONEf_KEEP_PTR_TABLE | CLONEf_CLONE_HOST);
47ba8780 507#else
fc04eb16 508 thread->interp = perl_clone(aTHX, CLONEf_KEEP_PTR_TABLE);
47ba8780 509#endif
47ba8780 510
fc04eb16 511 /* perl_clone() leaves us in new interpreter's context. As it is tricky
512 * to spot an implicit aTHX, create a new scope with aTHX matching the
513 * context for the duration of our work for new interpreter.
514 */
515 {
516 dTHXa(thread->interp);
517
518 MY_CXT_CLONE;
519
520 /* Here we remove END blocks since they should only run in the thread
521 * they are created
522 */
523 SvREFCNT_dec(PL_endav);
524 PL_endav = newAV();
404aaa48 525
f2e0bb91 526 if (SvPOK(init_function)) {
527 thread->init_function = newSV(0);
528 sv_copypv(thread->init_function, init_function);
529 } else {
530 clone_param.flags = 0;
531 thread->init_function = sv_dup(init_function, &clone_param);
532 if (SvREFCNT(thread->init_function) == 0) {
533 SvREFCNT_inc(thread->init_function);
534 }
fc04eb16 535 }
536
537 thread->params = sv_dup(params, &clone_param);
538 SvREFCNT_inc(thread->params);
539
540 /* The code below checks that anything living on the tmps stack and
541 * has been cloned (so it lives in the ptr_table) has a refcount
542 * higher than 0.
543 *
544 * If the refcount is 0 it means that a something on the stack/context
545 * was holding a reference to it and since we init_stacks() in
546 * perl_clone that won't get cleaned and we will get a leaked scalar.
547 * The reason it was cloned was that it lived on the @_ stack.
548 *
549 * Example of this can be found in bugreport 15837 where calls in the
550 * parameter list end up as a temp.
551 *
552 * One could argue that this fix should be in perl_clone.
553 */
554 while (tmps_ix > 0) {
555 SV* sv = (SV*)ptr_table_fetch(PL_ptr_table, tmps_tmp[tmps_ix]);
556 tmps_ix--;
557 if (sv && SvREFCNT(sv) == 0) {
558 SvREFCNT_inc(sv);
559 SvREFCNT_dec(sv);
560 }
561 }
562
563 SvTEMP_off(thread->init_function);
564 ptr_table_free(PL_ptr_table);
565 PL_ptr_table = NULL;
566 PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
567 }
568 S_ithread_set(aTHX_ current_thread);
569 PERL_SET_CONTEXT(aTHX);
570
571 /* Create/start the thread */
47ba8780 572#ifdef WIN32
fc04eb16 573 thread->handle = CreateThread(NULL,
514612b7 574 (DWORD)thread->stack_size,
fc04eb16 575 S_ithread_run,
576 (LPVOID)thread,
514612b7 577 STACK_SIZE_PARAM_IS_A_RESERVATION,
fc04eb16 578 &thread->thr);
82c40bf6 579#else
fc04eb16 580 {
581 static pthread_attr_t attr;
582 static int attr_inited = 0;
583 static int attr_joinable = PTHREAD_CREATE_JOINABLE;
584 if (! attr_inited) {
585 pthread_attr_init(&attr);
586 attr_inited = 1;
587 }
588
fa26028c 589# ifdef PTHREAD_ATTR_SETDETACHSTATE
fc04eb16 590 /* Threads start out joinable */
591 PTHREAD_ATTR_SETDETACHSTATE(&attr, attr_joinable);
fa26028c 592# endif
fc04eb16 593
514612b7 594# ifdef _POSIX_THREAD_ATTR_STACKSIZE
fc04eb16 595 /* Set thread's stack size */
514612b7 596 if (thread->stack_size > 0) {
597 rc_stack_size = pthread_attr_setstacksize(&attr, (size_t)thread->stack_size);
598 }
3eb37d38 599# endif
600
fc04eb16 601 /* Create the thread */
602 if (! rc_stack_size) {
603# ifdef OLD_PTHREADS_API
604 rc_thread_create = pthread_create(&thread->thr,
605 attr,
606 S_ithread_run,
607 (void *)thread);
608# else
609# if defined(HAS_PTHREAD_ATTR_SETSCOPE) && defined(PTHREAD_SCOPE_SYSTEM)
610 pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);
611# endif
612 rc_thread_create = pthread_create(&thread->thr,
613 &attr,
614 S_ithread_run,
615 (void *)thread);
19a077f6 616# endif
fc04eb16 617 }
514612b7 618
619# ifdef _POSIX_THREAD_ATTR_STACKSIZE
620 /* Try to get thread's actual stack size */
621 {
622 size_t stacksize;
58a3a76c 623#ifdef HPUX1020
624 stacksize = pthread_attr_getstacksize(attr);
625#else
626 if (! pthread_attr_getstacksize(&attr, &stacksize))
627#endif
628 if (stacksize > 0) {
514612b7 629 thread->stack_size = (IV)stacksize;
630 }
514612b7 631 }
632# endif
fc04eb16 633 }
82c40bf6 634#endif
bcd9ca9b 635
fc04eb16 636 /* Check for errors */
d94006e8 637#ifdef WIN32
fc04eb16 638 if (thread->handle == NULL) {
d94006e8 639#else
fc04eb16 640 if (rc_stack_size || rc_thread_create) {
d94006e8 641#endif
fc04eb16 642 MUTEX_UNLOCK(&create_destruct_mutex);
643 sv_2mortal(params);
644 S_ithread_destruct(aTHX_ thread);
d94006e8 645#ifndef WIN32
514612b7 646 if (ckWARN_d(WARN_THREADS)) {
647 if (rc_stack_size)
648 Perl_warn(aTHX_ "Thread creation failed: pthread_attr_setstacksize(%" IVdf ") returned %d", thread->stack_size, rc_stack_size);
649 else
650 Perl_warn(aTHX_ "Thread creation failed: pthread_create returned %d", rc_thread_create);
651 }
d94006e8 652#endif
fc04eb16 653 return (&PL_sv_undef);
654 }
655
656 active_threads++;
657 MUTEX_UNLOCK(&create_destruct_mutex);
658
659 sv_2mortal(params);
3b1c3273 660
fc04eb16 661 return (ithread_to_SV(aTHX_ obj, thread, classname, FALSE));
68795e93 662}
47ba8780 663
73e09c8f 664#endif /* USE_ITHREADS */
e1c44605 665
fcea4b7c 666
fc04eb16 667MODULE = threads PACKAGE = threads PREFIX = ithread_
68795e93 668PROTOTYPES: DISABLE
8222d950 669
73e09c8f 670#ifdef USE_ITHREADS
671
68795e93 672void
f4cc38af 673ithread_create(...)
674 PREINIT:
675 char *classname;
514612b7 676 ithread *thread;
f4cc38af 677 SV *function_to_call;
678 AV *params;
514612b7 679 HV *specs;
680 IV stack_size;
9d9ff5b1 681 int context;
682 char *str;
683 char ch;
514612b7 684 int idx;
f4cc38af 685 int ii;
686 CODE:
514612b7 687 if ((items >= 2) && SvROK(ST(1)) && SvTYPE(SvRV(ST(1)))==SVt_PVHV) {
688 if (--items < 2)
689 Perl_croak(aTHX_ "Usage: threads->create(\\%specs, function, ...)");
690 specs = (HV*)SvRV(ST(1));
691 idx = 1;
692 } else {
693 if (items < 2)
694 Perl_croak(aTHX_ "Usage: threads->create(function, ...)");
695 specs = NULL;
696 idx = 0;
697 }
f4cc38af 698
514612b7 699 if (sv_isobject(ST(0))) {
700 /* $thr->create() */
701 classname = HvNAME(SvSTASH(SvRV(ST(0))));
702 thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
703 stack_size = thread->stack_size;
704 } else {
705 /* threads->create() */
706 classname = (char *)SvPV_nolen(ST(0));
707 stack_size = default_stack_size;
708 }
709
710 function_to_call = ST(idx+1);
711
9d9ff5b1 712 context = -1;
514612b7 713 if (specs) {
714 /* stack_size */
715 if (hv_exists(specs, "stack", 5)) {
716 stack_size = SvIV(*hv_fetch(specs, "stack", 5, 0));
717 } else if (hv_exists(specs, "stacksize", 9)) {
718 stack_size = SvIV(*hv_fetch(specs, "stacksize", 9, 0));
719 } else if (hv_exists(specs, "stack_size", 10)) {
720 stack_size = SvIV(*hv_fetch(specs, "stack_size", 10, 0));
721 }
9d9ff5b1 722
723 /* context */
724 if (hv_exists(specs, "context", 7)) {
725 str = (char *)SvPV_nolen(*hv_fetch(specs, "context", 7, 0));
726 switch (*str) {
727 case 'a':
728 case 'A':
729 context = G_ARRAY;
730 break;
731 case 's':
732 case 'S':
733 context = G_SCALAR;
734 break;
735 case 'v':
736 case 'V':
737 context = G_VOID;
738 break;
739 default:
740 Perl_croak(aTHX_ "Invalid context: %s", str);
741 }
742 } else if (hv_exists(specs, "array", 5)) {
743 if (SvTRUE(*hv_fetch(specs, "array", 5, 0))) {
744 context = G_ARRAY;
745 }
746 } else if (hv_exists(specs, "scalar", 6)) {
747 if (SvTRUE(*hv_fetch(specs, "scalar", 6, 0))) {
748 context = G_SCALAR;
749 }
750 } else if (hv_exists(specs, "void", 4)) {
751 if (SvTRUE(*hv_fetch(specs, "void", 4, 0))) {
752 context = G_VOID;
753 }
754 }
755 }
756 if (context == -1) {
757 context = GIMME_V; /* Implicit context */
758 } else {
759 context |= (GIMME_V & (~(G_ARRAY|G_SCALAR|G_VOID)));
514612b7 760 }
f4cc38af 761
762 /* Function args */
763 params = newAV();
764 if (items > 2) {
514612b7 765 for (ii=2; ii < items ; ii++) {
766 av_push(params, SvREFCNT_inc(ST(idx+ii)));
f4cc38af 767 }
768 }
769
770 /* Create thread */
bcd9ca9b 771 ST(0) = sv_2mortal(S_ithread_create(aTHX_ Nullsv,
514612b7 772 classname,
773 function_to_call,
774 stack_size,
9d9ff5b1 775 context,
514612b7 776 newRV_noinc((SV*)params)));
f4cc38af 777 /* XSRETURN(1); - implied */
778
8222d950 779
68795e93 780void
f4cc38af 781ithread_list(...)
782 PREINIT:
783 char *classname;
fc04eb16 784 ithread *thread;
f4cc38af 785 int list_context;
786 IV count = 0;
787 PPCODE:
788 /* Class method only */
789 if (SvROK(ST(0)))
790 Perl_croak(aTHX_ "Usage: threads->list()");
791 classname = (char *)SvPV_nolen(ST(0));
792
793 /* Calling context */
794 list_context = (GIMME_V == G_ARRAY);
795
796 /* Walk through threads list */
797 MUTEX_LOCK(&create_destruct_mutex);
fc04eb16 798 for (thread = threads->next;
799 thread != threads;
800 thread = thread->next)
f4cc38af 801 {
802 /* Ignore detached or joined threads */
fc04eb16 803 if (thread->state & (PERL_ITHR_DETACHED|PERL_ITHR_JOINED)) {
f4cc38af 804 continue;
805 }
806 /* Push object on stack if list context */
807 if (list_context) {
fc04eb16 808 XPUSHs(sv_2mortal(ithread_to_SV(aTHX_ Nullsv, thread, classname, TRUE)));
f4cc38af 809 }
810 count++;
811 }
812 MUTEX_UNLOCK(&create_destruct_mutex);
813 /* If scalar context, send back count */
814 if (! list_context) {
815 XSRETURN_IV(count);
816 }
678a9b6c 817
818
819void
f4cc38af 820ithread_self(...)
821 PREINIT:
822 char *classname;
fcea4b7c 823 ithread *thread;
f4cc38af 824 CODE:
825 /* Class method only */
826 if (SvROK(ST(0)))
827 Perl_croak(aTHX_ "Usage: threads->self()");
828 classname = (char *)SvPV_nolen(ST(0));
829
fcea4b7c 830 thread = S_ithread_get(aTHX);
831
832 ST(0) = sv_2mortal(ithread_to_SV(aTHX_ Nullsv, thread, classname, TRUE));
f4cc38af 833 /* XSRETURN(1); - implied */
47ba8780 834
47ba8780 835
836void
f4cc38af 837ithread_tid(...)
838 PREINIT:
839 ithread *thread;
840 CODE:
841 thread = SV_to_ithread(aTHX_ ST(0));
842 XST_mUV(0, thread->tid);
843 /* XSRETURN(1); - implied */
844
e1c44605 845
f9dff5f5 846void
f4cc38af 847ithread_join(...)
848 PREINIT:
fcea4b7c 849 ithread *thread;
850 int join_err;
f4cc38af 851 AV *params;
852 int len;
853 int ii;
fcea4b7c 854#ifdef WIN32
855 DWORD waitcode;
856#else
857 void *retval;
858#endif
f4cc38af 859 PPCODE:
860 /* Object method only */
861 if (! sv_isobject(ST(0)))
862 Perl_croak(aTHX_ "Usage: $thr->join()");
863
fcea4b7c 864 /* Check if the thread is joinable */
865 thread = SV_to_ithread(aTHX_ ST(0));
866 MUTEX_LOCK(&thread->mutex);
867 join_err = (thread->state & (PERL_ITHR_DETACHED|PERL_ITHR_JOINED));
868 MUTEX_UNLOCK(&thread->mutex);
869 if (join_err) {
870 if (join_err & PERL_ITHR_DETACHED) {
871 Perl_croak(aTHX_ "Cannot join a detached thread");
872 } else {
873 Perl_croak(aTHX_ "Thread already joined");
874 }
875 }
876
877 /* Join the thread */
878#ifdef WIN32
879 waitcode = WaitForSingleObject(thread->handle, INFINITE);
880#else
881 pthread_join(thread->thr, &retval);
882#endif
883
884 MUTEX_LOCK(&thread->mutex);
885 /* Mark as joined */
886 thread->state |= PERL_ITHR_JOINED;
887
888 /* Get the return value from the call_sv */
889 {
890 AV *params_copy;
891 PerlInterpreter *other_perl;
892 CLONE_PARAMS clone_params;
893 ithread *current_thread;
894
895 params_copy = (AV *)SvRV(thread->params);
896 other_perl = thread->interp;
897 clone_params.stashes = newAV();
898 clone_params.flags = CLONEf_JOIN_IN;
899 PL_ptr_table = ptr_table_new();
900 current_thread = S_ithread_get(aTHX);
901 S_ithread_set(aTHX_ thread);
902 /* Ensure 'meaningful' addresses retain their meaning */
903 ptr_table_store(PL_ptr_table, &other_perl->Isv_undef, &PL_sv_undef);
904 ptr_table_store(PL_ptr_table, &other_perl->Isv_no, &PL_sv_no);
905 ptr_table_store(PL_ptr_table, &other_perl->Isv_yes, &PL_sv_yes);
906 params = (AV *)sv_dup((SV*)params_copy, &clone_params);
907 S_ithread_set(aTHX_ current_thread);
908 SvREFCNT_dec(clone_params.stashes);
909 SvREFCNT_inc(params);
910 ptr_table_free(PL_ptr_table);
911 PL_ptr_table = NULL;
912 }
913
914 /* We are finished with the thread */
915 S_ithread_clear(aTHX_ thread);
916 MUTEX_UNLOCK(&thread->mutex);
917
918 /* If no return values, then just return */
f4cc38af 919 if (! params) {
920 XSRETURN_UNDEF;
921 }
922
923 /* Put return values on stack */
924 len = (int)AvFILL(params);
925 for (ii=0; ii <= len; ii++) {
926 SV* param = av_shift(params);
927 XPUSHs(sv_2mortal(param));
928 }
929
930 /* Free return value array */
931 SvREFCNT_dec(params);
932
933
934void
935ithread_yield(...)
936 CODE:
937 YIELD;
938
939
940void
941ithread_detach(...)
942 PREINIT:
943 ithread *thread;
fcea4b7c 944 int detach_err;
945 int cleanup;
f4cc38af 946 CODE:
947 thread = SV_to_ithread(aTHX_ ST(0));
fcea4b7c 948 MUTEX_LOCK(&thread->mutex);
949
950 /* Check if the thread is detachable */
951 if ((detach_err = (thread->state & (PERL_ITHR_DETACHED|PERL_ITHR_JOINED)))) {
952 MUTEX_UNLOCK(&thread->mutex);
953 if (detach_err & PERL_ITHR_DETACHED) {
954 Perl_croak(aTHX_ "Thread already detached");
955 } else {
956 Perl_croak(aTHX_ "Cannot detach a joined thread");
957 }
958 }
959
960 /* Detach the thread */
961 thread->state |= PERL_ITHR_DETACHED;
962#ifdef WIN32
963 /* Windows has no 'detach thread' function */
964#else
965 PERL_THREAD_DETACH(thread->thr);
966#endif
967 /* Cleanup if finished */
968 cleanup = (thread->state & PERL_ITHR_FINISHED);
969 MUTEX_UNLOCK(&thread->mutex);
970
971 if (cleanup)
972 S_ithread_destruct(aTHX_ thread);
f4cc38af 973
47ba8780 974
975void
c0003851 976ithread_kill(...)
977 PREINIT:
978 ithread *thread;
979 char *sig_name;
980 IV signal;
981 CODE:
982 /* Must have safe signals */
983 if (PL_signals & PERL_SIGNALS_UNSAFE_FLAG)
984 Perl_croak(aTHX_ "Cannot signal other threads without safe signals");
985
986 /* Object method only */
987 if (! sv_isobject(ST(0)))
988 Perl_croak(aTHX_ "Usage: $thr->kill('SIG...')");
989
990 /* Get thread */
991 thread = SV_to_ithread(aTHX_ ST(0));
992
993 /* Get signal */
994 sig_name = SvPV_nolen(ST(1));
995 if (isALPHA(*sig_name)) {
996 if (*sig_name == 'S' && sig_name[1] == 'I' && sig_name[2] == 'G')
997 sig_name += 3;
404aaa48 998 if ((signal = whichsig(sig_name)) < 0)
c0003851 999 Perl_croak(aTHX_ "Unrecognized signal name: %s", sig_name);
1000 } else
1001 signal = SvIV(ST(1));
1002
1003 /* Set the signal for the thread */
1004 {
1005 dTHXa(thread->interp);
1006 PL_psig_pend[signal]++;
1007 PL_sig_pending = 1;
1008 }
1009
1010 /* Return the thread to allow for method chaining */
1011 ST(0) = ST(0);
1012 /* XSRETURN(1); - implied */
1013
1014
1015void
f4cc38af 1016ithread_DESTROY(...)
1017 CODE:
fcea4b7c 1018 sv_unmagic(SvRV(ST(0)), PERL_MAGIC_shared_scalar);
f4cc38af 1019
1020
1021void
1022ithread_equal(...)
fc04eb16 1023 PREINIT:
1024 int are_equal = 0;
f4cc38af 1025 CODE:
fc04eb16 1026 /* Compares TIDs to determine thread equality */
f4cc38af 1027 if (sv_isobject(ST(0)) && sv_isobject(ST(1))) {
1028 ithread *thr1 = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1029 ithread *thr2 = INT2PTR(ithread *, SvIV(SvRV(ST(1))));
fc04eb16 1030 are_equal = (thr1->tid == thr2->tid);
1031 }
1032 if (are_equal) {
1033 XST_mYES(0);
f4cc38af 1034 } else {
fc04eb16 1035 /* Return 0 on false for backward compatibility */
f4cc38af 1036 XST_mIV(0, 0);
1037 }
1038 /* XSRETURN(1); - implied */
1039
47ba8780 1040
47ba8780 1041void
f4cc38af 1042ithread_object(...)
1043 PREINIT:
1044 char *classname;
1045 UV tid;
fc04eb16 1046 ithread *thread;
f4cc38af 1047 int found = 0;
1048 CODE:
1049 /* Class method only */
1050 if (SvROK(ST(0)))
1051 Perl_croak(aTHX_ "Usage: threads->object($tid)");
1052 classname = (char *)SvPV_nolen(ST(0));
1053
1054 if ((items < 2) || ! SvOK(ST(1))) {
1055 XSRETURN_UNDEF;
1056 }
1057
fc04eb16 1058 /* threads->object($tid) */
f4cc38af 1059 tid = SvUV(ST(1));
1060
1061 /* Walk through threads list */
1062 MUTEX_LOCK(&create_destruct_mutex);
fc04eb16 1063 for (thread = threads->next;
1064 thread != threads;
1065 thread = thread->next)
f4cc38af 1066 {
1067 /* Look for TID, but ignore detached or joined threads */
fc04eb16 1068 if ((thread->tid != tid) ||
1069 (thread->state & (PERL_ITHR_DETACHED|PERL_ITHR_JOINED)))
f4cc38af 1070 {
1071 continue;
1072 }
1073 /* Put object on stack */
fc04eb16 1074 ST(0) = sv_2mortal(ithread_to_SV(aTHX_ Nullsv, thread, classname, TRUE));
f4cc38af 1075 found = 1;
1076 break;
1077 }
1078 MUTEX_UNLOCK(&create_destruct_mutex);
1079 if (! found) {
1080 XSRETURN_UNDEF;
1081 }
1082 /* XSRETURN(1); - implied */
1083
1084
1085void
1086ithread__handle(...);
1087 PREINIT:
1088 ithread *thread;
1089 CODE:
1090 thread = SV_to_ithread(aTHX_ ST(0));
1091#ifdef WIN32
fcea4b7c 1092 XST_mUV(0, PTR2UV(&thread->handle));
f4cc38af 1093#else
75ba4ae2 1094 XST_mUV(0, PTR2UV(&thread->thr));
f4cc38af 1095#endif
1096 /* XSRETURN(1); - implied */
68795e93 1097
514612b7 1098
1099void
1100ithread_get_stack_size(...)
1101 PREINIT:
1102 IV stack_size;
1103 CODE:
1104 if (sv_isobject(ST(0))) {
1105 /* $thr->get_stack_size() */
1106 ithread *thread = INT2PTR(ithread *, SvIV(SvRV(ST(0))));
1107 stack_size = thread->stack_size;
1108 } else {
1109 /* threads->get_stack_size() */
1110 stack_size = default_stack_size;
1111 }
1112 XST_mIV(0, stack_size);
1113 /* XSRETURN(1); - implied */
1114
1115
1116void
1117ithread_set_stack_size(...)
1118 PREINIT:
1119 IV old_size;
1120 CODE:
1121 if (items != 2)
1122 Perl_croak(aTHX_ "Usage: threads->set_stack_size($size)");
1123 if (sv_isobject(ST(0)))
1124 Perl_croak(aTHX_ "Cannot change stack size of an existing thread");
1125
1126 old_size = default_stack_size;
1127 default_stack_size = good_stack_size(aTHX_ SvIV(ST(1)));
1128 XST_mIV(0, old_size);
1129 /* XSRETURN(1); - implied */
1130
73e09c8f 1131#endif /* USE_ITHREADS */
1132
fc04eb16 1133
68795e93 1134BOOT:
1135{
73e09c8f 1136#ifdef USE_ITHREADS
fc04eb16 1137 /* The 'main' thread is thread 0.
1138 * It is detached (unjoinable) and immortal.
1139 */
62375a60 1140
fc04eb16 1141 ithread *thread;
1142 MY_CXT_INIT;
1143
1144 PL_perl_destruct_level = 2;
1145 MUTEX_INIT(&create_destruct_mutex);
1146 MUTEX_LOCK(&create_destruct_mutex);
1147
1148 PL_threadhook = &Perl_ithread_hook;
1149
1150 thread = (ithread *)PerlMemShared_malloc(sizeof(ithread));
1151 if (! thread) {
1152 PerlLIO_write(PerlIO_fileno(Perl_error_log), PL_no_mem, strlen(PL_no_mem));
1153 my_exit(1);
1154 }
1155 Zero(thread, 1, ithread);
1156
1157 PL_perl_destruct_level = 2;
1158 MUTEX_INIT(&thread->mutex);
1159
1160 thread->tid = tid_counter++; /* Thread 0 */
1161
1162 /* Head of the threads list */
1163 threads = thread;
1164 thread->next = thread;
1165 thread->prev = thread;
1166
1167 thread->count = 1; /* Immortal */
1168
1169 thread->interp = aTHX;
1170 thread->state = PERL_ITHR_DETACHED; /* Detached */
514612b7 1171 thread->stack_size = default_stack_size;
fc04eb16 1172# ifdef WIN32
1173 thread->thr = GetCurrentThreadId();
1174# else
1175 thread->thr = pthread_self();
1176# endif
1177
1178 active_threads++;
1179
1180 S_ithread_set(aTHX_ thread);
1181 MUTEX_UNLOCK(&create_destruct_mutex);
73e09c8f 1182#endif /* USE_ITHREADS */
68795e93 1183}