As suggested by Arthur: the threads and threads::shared
[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"
5
73e09c8f 6#ifdef USE_ITHREADS
7
68795e93 8#ifdef WIN32
9#include <windows.h>
10#include <win32thread.h>
11#define PERL_THREAD_SETSPECIFIC(k,v) TlsSetValue(k,v)
12#define PERL_THREAD_GETSPECIFIC(k,v) v = TlsGetValue(k)
13#define PERL_THREAD_ALLOC_SPECIFIC(k) \
14STMT_START {\
15 if((k = TlsAlloc()) == TLS_OUT_OF_INDEXES) {\
16 PerlIO_printf(PerlIO_stderr(),"panic threads.h: TlsAlloc");\
17 exit(1);\
18 }\
19} STMT_END
20#else
21#include <pthread.h>
22#include <thread.h>
23
24#define PERL_THREAD_SETSPECIFIC(k,v) pthread_setspecific(k,v)
25#ifdef OLD_PTHREADS_API
26#define PERL_THREAD_DETACH(t) pthread_detach(&(t))
27#define PERL_THREAD_GETSPECIFIC(k,v) pthread_getspecific(k,&v)
28#define PERL_THREAD_ALLOC_SPECIFIC(k) STMT_START {\
29 if(pthread_keycreate(&(k),0)) {\
30 PerlIO_printf(PerlIO_stderr(), "panic threads.h: pthread_key_create");\
31 exit(1);\
32 }\
33} STMT_END
34#else
35#define PERL_THREAD_DETACH(t) pthread_detach((t))
36#define PERL_THREAD_GETSPECIFIC(k,v) v = pthread_getspecific(k)
37#define PERL_THREAD_ALLOC_SPECIFIC(k) STMT_START {\
38 if(pthread_key_create(&(k),0)) {\
39 PerlIO_printf(PerlIO_stderr(), "panic threads.h: pthread_key_create");\
40 exit(1);\
41 }\
42} STMT_END
43#endif
44#endif
45
62375a60 46/* Values for 'state' member */
47#define PERL_ITHR_JOINABLE 0
48#define PERL_ITHR_DETACHED 1
49#define PERL_ITHR_FINISHED 4
50#define PERL_ITHR_JOINED 2
51
68795e93 52typedef struct ithread_s {
53 struct ithread_s *next; /* next thread in the list */
54 struct ithread_s *prev; /* prev thread in the list */
55 PerlInterpreter *interp; /* The threads interpreter */
56 I32 tid; /* threads module's thread id */
57 perl_mutex mutex; /* mutex for updating things in this struct */
58 I32 count; /* how many SVs have a reference to us */
62375a60 59 signed char state; /* are we detached ? */
a446a88f 60 int gimme; /* Context of create */
68795e93 61 SV* init_function; /* Code to run */
62 SV* params; /* args to pass function */
63#ifdef WIN32
64 DWORD thr; /* OS's idea if thread id */
65 HANDLE handle; /* OS's waitable handle */
66#else
67 pthread_t thr; /* OS's handle for the thread */
68#endif
69} ithread;
70
71ithread *threads;
72
73/* Macros to supply the aTHX_ in an embed.h like manner */
74#define ithread_join(thread) Perl_ithread_join(aTHX_ thread)
75#define ithread_DESTROY(thread) Perl_ithread_DESTROY(aTHX_ thread)
76#define ithread_CLONE(thread) Perl_ithread_CLONE(aTHX_ thread)
77#define ithread_detach(thread) Perl_ithread_detach(aTHX_ thread)
78#define ithread_tid(thread) ((thread)->tid)
79
58c2ef19 80static perl_mutex create_destruct_mutex; /* protects the creation and destruction of threads*/
68795e93 81
82I32 tid_counter = 0;
62375a60 83I32 known_threads = 0;
58c2ef19 84I32 active_threads = 0;
68795e93 85perl_key self_key;
86
87/*
88 * Clear up after thread is done with
89 */
90void
62375a60 91Perl_ithread_destruct (pTHX_ ithread* thread, const char *why)
68795e93 92{
93 MUTEX_LOCK(&thread->mutex);
62375a60 94 if (!thread->next) {
95 Perl_croak(aTHX_ "panic: destruct destroyed thread %p (%s)",thread, why);
96 }
68795e93 97 if (thread->count != 0) {
98 MUTEX_UNLOCK(&thread->mutex);
d1400e48 99 return;
68795e93 100 }
58c2ef19 101 MUTEX_LOCK(&create_destruct_mutex);
68795e93 102 /* Remove from circular list of threads */
103 if (thread->next == thread) {
104 /* last one should never get here ? */
105 threads = NULL;
106 }
107 else {
108 thread->next->prev = thread->prev->next;
109 thread->prev->next = thread->next->prev;
110 if (threads == thread) {
111 threads = thread->next;
112 }
62375a60 113 thread->next = NULL;
114 thread->prev = NULL;
68795e93 115 }
62375a60 116 known_threads--;
117 assert( known_threads >= 0 );
ba14dd9a 118#if 0
62375a60 119 Perl_warn(aTHX_ "destruct %d @ %p by %p now %d",
120 thread->tid,thread->interp,aTHX, known_threads);
ba14dd9a 121#endif
62375a60 122 MUTEX_UNLOCK(&create_destruct_mutex);
123 /* Thread is now disowned */
68795e93 124 if (thread->interp) {
68795e93 125 PERL_SET_CONTEXT(thread->interp);
126 perl_destruct(thread->interp);
127 perl_free(thread->interp);
128 thread->interp = NULL;
129 }
130 PERL_SET_CONTEXT(aTHX);
d1400e48 131 MUTEX_UNLOCK(&thread->mutex);
68795e93 132}
133
62375a60 134int
135Perl_ithread_hook(pTHX)
136{
137 int veto_cleanup = 0;
138 MUTEX_LOCK(&create_destruct_mutex);
139 if (aTHX == PL_curinterp && active_threads != 1) {
140 Perl_warn(aTHX_ "Cleanup skipped %d active threads", active_threads);
141 veto_cleanup = 1;
142 }
143 MUTEX_UNLOCK(&create_destruct_mutex);
144 return veto_cleanup;
145}
146
147void
148Perl_ithread_detach(pTHX_ ithread *thread)
149{
150 MUTEX_LOCK(&thread->mutex);
151 if (!(thread->state & (PERL_ITHR_DETACHED|PERL_ITHR_JOINED))) {
152 thread->state |= PERL_ITHR_DETACHED;
153#ifdef WIN32
154 CloseHandle(thread->handle);
155 thread->handle = 0;
156#else
157 PERL_THREAD_DETACH(thread->thr);
158#endif
159 }
160 if ((thread->state & PERL_ITHR_FINISHED) &&
161 (thread->state & PERL_ITHR_DETACHED)) {
162 MUTEX_UNLOCK(&thread->mutex);
163 Perl_ithread_destruct(aTHX_ thread, "detach");
164 }
165 else {
166 MUTEX_UNLOCK(&thread->mutex);
167 }
168}
68795e93 169
170/* MAGIC (in mg.h sense) hooks */
171
172int
173ithread_mg_get(pTHX_ SV *sv, MAGIC *mg)
174{
175 ithread *thread = (ithread *) mg->mg_ptr;
176 SvIVX(sv) = PTR2IV(thread);
177 SvIOK_on(sv);
178 return 0;
179}
180
181int
182ithread_mg_free(pTHX_ SV *sv, MAGIC *mg)
183{
184 ithread *thread = (ithread *) mg->mg_ptr;
185 MUTEX_LOCK(&thread->mutex);
68795e93 186 thread->count--;
62375a60 187 if (thread->count == 0) {
188 if (!(thread->state & (PERL_ITHR_DETACHED|PERL_ITHR_JOINED))) {
189 Perl_warn(aTHX_ "Implicit detach");
190 }
191 MUTEX_UNLOCK(&thread->mutex);
192 Perl_ithread_detach(aTHX_ thread);
193 }
194 else {
195 MUTEX_UNLOCK(&thread->mutex);
196 }
68795e93 197 return 0;
198}
199
200int
201ithread_mg_dup(pTHX_ MAGIC *mg, CLONE_PARAMS *param)
202{
203 ithread *thread = (ithread *) mg->mg_ptr;
204 MUTEX_LOCK(&thread->mutex);
68795e93 205 thread->count++;
206 MUTEX_UNLOCK(&thread->mutex);
207 return 0;
208}
209
210MGVTBL ithread_vtbl = {
211 ithread_mg_get, /* get */
212 0, /* set */
213 0, /* len */
214 0, /* clear */
215 ithread_mg_free, /* free */
216 0, /* copy */
217 ithread_mg_dup /* dup */
218};
219
47ba8780 220
47ba8780 221/*
b1edfb69 222 * Starts executing the thread. Needs to clean up memory a tad better.
68795e93 223 * Passed as the C level function to run in the new thread
b1edfb69 224 */
47ba8780 225
226#ifdef WIN32
68795e93 227THREAD_RET_TYPE
228Perl_ithread_run(LPVOID arg) {
47ba8780 229#else
68795e93 230void*
231Perl_ithread_run(void * arg) {
47ba8780 232#endif
5b414d21 233 ithread* thread = (ithread*) arg;
47ba8780 234 dTHXa(thread->interp);
47ba8780 235 PERL_SET_CONTEXT(thread->interp);
68795e93 236 PERL_THREAD_SETSPECIFIC(self_key,thread);
47ba8780 237
68795e93 238#if 0
239 /* Far from clear messing with ->thr child-side is a good idea */
240 MUTEX_LOCK(&thread->mutex);
47ba8780 241#ifdef WIN32
242 thread->thr = GetCurrentThreadId();
243#else
244 thread->thr = pthread_self();
245#endif
68795e93 246 MUTEX_UNLOCK(&thread->mutex);
247#endif
47ba8780 248
47ba8780 249 PL_perl_destruct_level = 2;
4f896ddc 250
47ba8780 251 {
68795e93 252 AV* params = (AV*) SvRV(thread->params);
253 I32 len = av_len(params)+1;
47ba8780 254 int i;
255 dSP;
47ba8780 256 ENTER;
257 SAVETMPS;
258 PUSHMARK(SP);
68795e93 259 for(i = 0; i < len; i++) {
260 XPUSHs(av_shift(params));
47ba8780 261 }
262 PUTBACK;
a446a88f 263 len = call_sv(thread->init_function, thread->gimme|G_EVAL);
68795e93 264 SPAGAIN;
a446a88f 265 for (i=len-1; i >= 0; i--) {
e1c44605 266 SV *sv = POPs;
267 av_store(params, i, SvREFCNT_inc(sv));
a446a88f 268 }
269 PUTBACK;
270 if (SvTRUE(ERRSV)) {
271 Perl_warn(aTHX_ "Died:%_",ERRSV);
272 }
47ba8780 273 FREETMPS;
274 LEAVE;
68795e93 275 SvREFCNT_dec(thread->init_function);
47ba8780 276 }
277
fd58862f 278 PerlIO_flush((PerlIO*)NULL);
62375a60 279 MUTEX_LOCK(&create_destruct_mutex);
280 active_threads--;
281 assert( active_threads >= 0 );
282 MUTEX_UNLOCK(&create_destruct_mutex);
68795e93 283 MUTEX_LOCK(&thread->mutex);
62375a60 284 thread->state |= PERL_ITHR_FINISHED;
285
286 if (thread->state & PERL_ITHR_DETACHED) {
47ba8780 287 MUTEX_UNLOCK(&thread->mutex);
a446a88f 288 SvREFCNT_dec(thread->params);
289 thread->params = Nullsv;
62375a60 290 Perl_ithread_destruct(aTHX_ thread, "detached finish");
47ba8780 291 } else {
62375a60 292 MUTEX_UNLOCK(&thread->mutex);
293 }
47ba8780 294#ifdef WIN32
295 return (DWORD)0;
e8f2bb9a 296#else
297 return 0;
47ba8780 298#endif
68795e93 299}
300
301SV *
302ithread_to_SV(pTHX_ SV *obj, ithread *thread, char *classname, bool inc)
303{
304 SV *sv;
305 MAGIC *mg;
306 if (inc) {
307 MUTEX_LOCK(&thread->mutex);
308 thread->count++;
68795e93 309 MUTEX_UNLOCK(&thread->mutex);
310 }
311 if (!obj)
312 obj = newSV(0);
313 sv = newSVrv(obj,classname);
314 sv_setiv(sv,PTR2IV(thread));
315 mg = sv_magicext(sv,Nullsv,PERL_MAGIC_shared_scalar,&ithread_vtbl,(char *)thread,0);
316 mg->mg_flags |= MGf_DUP;
317 SvREADONLY_on(sv);
318 return obj;
319}
47ba8780 320
68795e93 321ithread *
322SV_to_ithread(pTHX_ SV *sv)
323{
324 ithread *thread;
325 if (SvROK(sv))
326 {
327 thread = INT2PTR(ithread*, SvIV(SvRV(sv)));
328 }
329 else
330 {
331 PERL_THREAD_GETSPECIFIC(self_key,thread);
332 }
333 return thread;
47ba8780 334}
335
47ba8780 336/*
68795e93 337 * iThread->create(); ( aka iThread->new() )
338 * Called in context of parent thread
b1edfb69 339 */
47ba8780 340
68795e93 341SV *
342Perl_ithread_create(pTHX_ SV *obj, char* classname, SV* init_function, SV* params)
343{
344 ithread* thread;
345 CLONE_PARAMS clone_param;
346
58c2ef19 347 MUTEX_LOCK(&create_destruct_mutex);
68795e93 348 thread = PerlMemShared_malloc(sizeof(ithread));
349 Zero(thread,1,ithread);
350 thread->next = threads;
351 thread->prev = threads->prev;
352 thread->prev->next = thread;
353 /* Set count to 1 immediately in case thread exits before
354 * we return to caller !
355 */
356 thread->count = 1;
357 MUTEX_INIT(&thread->mutex);
358 thread->tid = tid_counter++;
a446a88f 359 thread->gimme = GIMME_V;
62375a60 360 thread->state = (thread->gimme == G_VOID) ? 1 : 0;
4f896ddc 361
68795e93 362 /* "Clone" our interpreter into the thread's interpreter
363 * This gives thread access to "static data" and code.
364 */
47ba8780 365
68795e93 366 PerlIO_flush((PerlIO*)NULL);
cd8c9bf8 367
47ba8780 368#ifdef WIN32
68795e93 369 thread->interp = perl_clone(aTHX, CLONEf_KEEP_PTR_TABLE | CLONEf_CLONE_HOST);
47ba8780 370#else
68795e93 371 thread->interp = perl_clone(aTHX, CLONEf_KEEP_PTR_TABLE);
47ba8780 372#endif
ba14dd9a 373 /* perl_clone leaves us in new interpreter's context.
374 As it is tricky to spot implcit aTHX create a new scope
a446a88f 375 with aTHX matching the context for the duration of
ba14dd9a 376 our work for new interpreter.
377 */
378 {
379 dTHXa(thread->interp);
58c2ef19 380 /* Here we remove END blocks since they should only run
62375a60 381 in the thread they are created
58c2ef19 382 */
383 SvREFCNT_dec(PL_endav);
384 PL_endav = newAV();
d1400e48 385 clone_param.flags = 0;
ba14dd9a 386 thread->init_function = sv_dup(init_function, &clone_param);
387 if (SvREFCNT(thread->init_function) == 0) {
388 SvREFCNT_inc(thread->init_function);
d1400e48 389 }
ba14dd9a 390
391 thread->params = sv_dup(params, &clone_param);
392 SvREFCNT_inc(thread->params);
393 SvTEMP_off(thread->init_function);
394 ptr_table_free(PL_ptr_table);
395 PL_ptr_table = NULL;
396 }
d1400e48 397
68795e93 398 PERL_SET_CONTEXT(aTHX);
47ba8780 399
68795e93 400 /* Start the thread */
47ba8780 401
402#ifdef WIN32
403
68795e93 404 thread->handle = CreateThread(NULL, 0, Perl_ithread_run,
47ba8780 405 (LPVOID)thread, 0, &thread->thr);
406
82c40bf6 407#else
fa26028c 408 {
409 static pthread_attr_t attr;
410 static int attr_inited = 0;
fa26028c 411 static int attr_joinable = PTHREAD_CREATE_JOINABLE;
412 if (!attr_inited) {
413 attr_inited = 1;
414 pthread_attr_init(&attr);
415 }
416# ifdef PTHREAD_ATTR_SETDETACHSTATE
417 PTHREAD_ATTR_SETDETACHSTATE(&attr, attr_joinable);
418# endif
3eb37d38 419# ifdef THREAD_CREATE_NEEDS_STACK
420 if(pthread_attr_setstacksize(&attr, THREAD_CREATE_NEEDS_STACK))
421 croak("panic: pthread_attr_setstacksize failed");
422# endif
423
3ad0b7d6 424#ifdef OLD_PTHREADS_API
68795e93 425 pthread_create( &thread->thr, attr, Perl_ithread_run, (void *)thread);
47ba8780 426#else
68795e93 427 pthread_create( &thread->thr, &attr, Perl_ithread_run, (void *)thread);
47ba8780 428#endif
3ad0b7d6 429 }
82c40bf6 430#endif
62375a60 431 known_threads++;
58c2ef19 432 active_threads++;
433 MUTEX_UNLOCK(&create_destruct_mutex);
68795e93 434 return ithread_to_SV(aTHX_ obj, thread, classname, FALSE);
435}
47ba8780 436
68795e93 437SV*
438Perl_ithread_self (pTHX_ SV *obj, char* Class)
439{
440 ithread *thread;
441 PERL_THREAD_GETSPECIFIC(self_key,thread);
442 return ithread_to_SV(aTHX_ obj, thread, Class, TRUE);
47ba8780 443}
444
445/*
e1c44605 446 * Joins the thread this code needs to take the returnvalue from the
68795e93 447 * call_sv and send it back
b1edfb69 448 */
47ba8780 449
68795e93 450void
451Perl_ithread_CLONE(pTHX_ SV *obj)
452{
453 if (SvROK(obj))
454 {
455 ithread *thread = SV_to_ithread(aTHX_ obj);
456 }
457 else
458 {
459 Perl_warn(aTHX_ "CLONE %_",obj);
460 }
47ba8780 461}
462
62375a60 463AV*
68795e93 464Perl_ithread_join(pTHX_ SV *obj)
465{
466 ithread *thread = SV_to_ithread(aTHX_ obj);
467 MUTEX_LOCK(&thread->mutex);
62375a60 468 if (thread->state & PERL_ITHR_DETACHED) {
a446a88f 469 MUTEX_UNLOCK(&thread->mutex);
470 Perl_croak(aTHX_ "Cannot join a detached thread");
471 }
62375a60 472 else if (thread->state & PERL_ITHR_JOINED) {
a446a88f 473 MUTEX_UNLOCK(&thread->mutex);
474 Perl_croak(aTHX_ "Thread already joined");
475 }
476 else {
e1c44605 477 AV* retparam;
47ba8780 478#ifdef WIN32
479 DWORD waitcode;
47ba8780 480#else
481 void *retval;
47ba8780 482#endif
47ba8780 483 MUTEX_UNLOCK(&thread->mutex);
68795e93 484#ifdef WIN32
485 waitcode = WaitForSingleObject(thread->handle, INFINITE);
486#else
487 pthread_join(thread->thr,&retval);
488#endif
47ba8780 489 MUTEX_LOCK(&thread->mutex);
e1c44605 490
62375a60 491 /* sv_dup over the args */
e1c44605 492 {
62375a60 493 AV* params = (AV*) SvRV(thread->params);
e1c44605 494 CLONE_PARAMS clone_params;
3275ba96 495 clone_params.stashes = newAV();
e1c44605 496 PL_ptr_table = ptr_table_new();
497 retparam = (AV*) sv_dup((SV*)params, &clone_params);
3275ba96 498 SvREFCNT_dec(clone_params.stashes);
e1c44605 499 SvREFCNT_inc(retparam);
500 ptr_table_free(PL_ptr_table);
501 PL_ptr_table = NULL;
502
503 }
a446a88f 504 /* We have finished with it */
62375a60 505 thread->state |= PERL_ITHR_JOINED;
47ba8780 506 MUTEX_UNLOCK(&thread->mutex);
68795e93 507 sv_unmagic(SvRV(obj),PERL_MAGIC_shared_scalar);
62375a60 508 Perl_ithread_destruct(aTHX_ thread, "joined");
e1c44605 509 return retparam;
68795e93 510 }
e1c44605 511 return (AV*)NULL;
47ba8780 512}
513
68795e93 514void
68795e93 515Perl_ithread_DESTROY(pTHX_ SV *sv)
516{
517 ithread *thread = SV_to_ithread(aTHX_ sv);
68795e93 518 sv_unmagic(SvRV(sv),PERL_MAGIC_shared_scalar);
519}
8222d950 520
73e09c8f 521#endif /* USE_ITHREADS */
e1c44605 522
68795e93 523MODULE = threads PACKAGE = threads PREFIX = ithread_
524PROTOTYPES: DISABLE
8222d950 525
73e09c8f 526#ifdef USE_ITHREADS
527
68795e93 528void
529ithread_new (classname, function_to_call, ...)
530char * classname
531SV * function_to_call
532CODE:
533{
534 AV* params = newAV();
535 if (items > 2) {
536 int i;
537 for(i = 2; i < items ; i++) {
538 av_push(params, ST(i));
539 }
540 }
541 ST(0) = sv_2mortal(Perl_ithread_create(aTHX_ Nullsv, classname, function_to_call, newRV_noinc((SV*) params)));
542 XSRETURN(1);
543}
8222d950 544
68795e93 545void
546ithread_self(char *classname)
547CODE:
548{
549 ST(0) = sv_2mortal(Perl_ithread_self(aTHX_ Nullsv,classname));
550 XSRETURN(1);
551}
47ba8780 552
553int
68795e93 554ithread_tid(ithread *thread)
47ba8780 555
556void
68795e93 557ithread_join(SV *obj)
e1c44605 558PPCODE:
559{
560 AV* params = Perl_ithread_join(aTHX_ obj);
561 int i;
562 I32 len = AvFILL(params);
563 for (i = 0; i <= len; i++) {
564 XPUSHs(av_shift(params));
565 }
566 SvREFCNT_dec(params);
567}
568
47ba8780 569
570void
68795e93 571ithread_detach(ithread *thread)
47ba8780 572
47ba8780 573void
68795e93 574ithread_DESTROY(SV *thread)
575
73e09c8f 576#endif /* USE_ITHREADS */
577
68795e93 578BOOT:
579{
73e09c8f 580#ifdef USE_ITHREADS
68795e93 581 ithread* thread;
e1c44605 582 PL_perl_destruct_level = 2;
68795e93 583 PERL_THREAD_ALLOC_SPECIFIC(self_key);
58c2ef19 584 MUTEX_INIT(&create_destruct_mutex);
585 MUTEX_LOCK(&create_destruct_mutex);
62375a60 586 PL_threadhook = &Perl_ithread_hook;
68795e93 587 thread = PerlMemShared_malloc(sizeof(ithread));
588 Zero(thread,1,ithread);
589 PL_perl_destruct_level = 2;
590 MUTEX_INIT(&thread->mutex);
591 threads = thread;
592 thread->next = thread;
593 thread->prev = thread;
594 thread->interp = aTHX;
595 thread->count = 1; /* imortal */
596 thread->tid = tid_counter++;
62375a60 597 known_threads++;
58c2ef19 598 active_threads++;
62375a60 599 thread->state = 1;
68795e93 600#ifdef WIN32
601 thread->thr = GetCurrentThreadId();
602#else
603 thread->thr = pthread_self();
604#endif
62375a60 605
68795e93 606 PERL_THREAD_SETSPECIFIC(self_key,thread);
58c2ef19 607 MUTEX_UNLOCK(&create_destruct_mutex);
73e09c8f 608#endif /* USE_ITHREADS */
68795e93 609}
610