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