753c8376f77420d73ab8ae1f35487e443b6ef8b2
[p5sagit/p5-mst-13.2.git] / ext / threads / threads.xs
1 #define PERL_NO_GET_CONTEXT
2 #include "EXTERN.h"
3 #include "perl.h"
4 #include "XSUB.h"
5
6 #ifdef USE_ITHREADS
7
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) \
14 STMT_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
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
52 typedef 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 */
59     signed char state;          /* are we detached ? */
60     int gimme;                  /* Context of create */
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
71 ithread *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 #define ithread_yield(thread)           (YIELD);
80
81 static perl_mutex create_destruct_mutex;  /* protects the creation and destruction of threads*/
82
83 I32 tid_counter = 0;
84 I32 known_threads = 0;
85 I32 active_threads = 0;
86 perl_key self_key;
87
88 /*
89  *  Clear up after thread is done with
90  */
91 void
92 Perl_ithread_destruct (pTHX_ ithread* thread, const char *why)
93 {
94         MUTEX_LOCK(&thread->mutex);
95         if (!thread->next) {
96             Perl_croak(aTHX_ "panic: destruct destroyed thread %p (%s)",thread, why);
97         }
98         if (thread->count != 0) {
99                 MUTEX_UNLOCK(&thread->mutex);
100                 return;
101         }
102         MUTEX_LOCK(&create_destruct_mutex);
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 {
109             thread->next->prev = thread->prev;
110             thread->prev->next = thread->next;
111             if (threads == thread) {
112                 threads = thread->next;
113             }
114             thread->next = NULL;
115             thread->prev = NULL;
116         }
117         known_threads--;
118         assert( known_threads >= 0 );
119 #if 0
120         Perl_warn(aTHX_ "destruct %d @ %p by %p now %d",
121                   thread->tid,thread->interp,aTHX, known_threads);
122 #endif
123         MUTEX_UNLOCK(&create_destruct_mutex);
124         /* Thread is now disowned */
125         if (thread->interp) {
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);
132         MUTEX_UNLOCK(&thread->mutex);
133 }
134
135 int
136 Perl_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
148 void
149 Perl_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 }
170
171 /* MAGIC (in mg.h sense) hooks */
172
173 int
174 ithread_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
182 int
183 ithread_mg_free(pTHX_ SV *sv, MAGIC *mg)
184 {
185     ithread *thread = (ithread *) mg->mg_ptr;
186     MUTEX_LOCK(&thread->mutex);
187     thread->count--;
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     }
198     return 0;
199 }
200
201 int
202 ithread_mg_dup(pTHX_ MAGIC *mg, CLONE_PARAMS *param)
203 {
204     ithread *thread = (ithread *) mg->mg_ptr;
205     MUTEX_LOCK(&thread->mutex);
206     thread->count++;
207     MUTEX_UNLOCK(&thread->mutex);
208     return 0;
209 }
210
211 MGVTBL 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
221
222 /*
223  *      Starts executing the thread. Needs to clean up memory a tad better.
224  *      Passed as the C level function to run in the new thread
225  */
226
227 #ifdef WIN32
228 THREAD_RET_TYPE
229 Perl_ithread_run(LPVOID arg) {
230 #else
231 void*
232 Perl_ithread_run(void * arg) {
233 #endif
234         ithread* thread = (ithread*) arg;
235         dTHXa(thread->interp);
236         PERL_SET_CONTEXT(thread->interp);
237         PERL_THREAD_SETSPECIFIC(self_key,thread);
238
239 #if 0
240         /* Far from clear messing with ->thr child-side is a good idea */
241         MUTEX_LOCK(&thread->mutex);
242 #ifdef WIN32
243         thread->thr = GetCurrentThreadId();
244 #else
245         thread->thr = pthread_self();
246 #endif
247         MUTEX_UNLOCK(&thread->mutex);
248 #endif
249
250         PL_perl_destruct_level = 2;
251
252         {
253                 AV* params = (AV*) SvRV(thread->params);
254                 I32 len = av_len(params)+1;
255                 int i;
256                 dSP;
257                 ENTER;
258                 SAVETMPS;
259                 PUSHMARK(SP);
260                 for(i = 0; i < len; i++) {
261                     XPUSHs(av_shift(params));
262                 }
263                 PUTBACK;
264                 len = call_sv(thread->init_function, thread->gimme|G_EVAL);
265                 SPAGAIN;
266                 for (i=len-1; i >= 0; i--) {
267                   SV *sv = POPs;
268                   av_store(params, i, SvREFCNT_inc(sv));
269                 }
270                 PUTBACK;
271                 if (SvTRUE(ERRSV)) {
272                     Perl_warn(aTHX_ "Died:%_",ERRSV);
273                 }
274                 FREETMPS;
275                 LEAVE;
276                 SvREFCNT_dec(thread->init_function);
277         }
278
279         PerlIO_flush((PerlIO*)NULL);
280         MUTEX_LOCK(&create_destruct_mutex);
281         active_threads--;
282         assert( active_threads >= 0 );
283         MUTEX_UNLOCK(&create_destruct_mutex);
284         MUTEX_LOCK(&thread->mutex);
285         thread->state |= PERL_ITHR_FINISHED;
286
287         if (thread->state & PERL_ITHR_DETACHED) {
288                 MUTEX_UNLOCK(&thread->mutex);
289                 SvREFCNT_dec(thread->params);
290                 thread->params = Nullsv;
291                 Perl_ithread_destruct(aTHX_ thread, "detached finish");
292         } else {
293                 MUTEX_UNLOCK(&thread->mutex);
294         }
295 #ifdef WIN32
296         return (DWORD)0;
297 #else
298         return 0;
299 #endif
300 }
301
302 SV *
303 ithread_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++;
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 }
321
322 ithread *
323 SV_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;
335 }
336
337 /*
338  * iThread->create(); ( aka iThread->new() )
339  * Called in context of parent thread
340  */
341
342 SV *
343 Perl_ithread_create(pTHX_ SV *obj, char* classname, SV* init_function, SV* params)
344 {
345         ithread*        thread;
346         CLONE_PARAMS    clone_param;
347
348         MUTEX_LOCK(&create_destruct_mutex);
349         thread = PerlMemShared_malloc(sizeof(ithread));
350         Zero(thread,1,ithread);
351         thread->next = threads;
352         thread->prev = threads->prev;
353         threads->prev = thread;
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++;
361         thread->gimme = GIMME_V;
362         thread->state = (thread->gimme == G_VOID) ? 1 : 0;
363
364         /* "Clone" our interpreter into the thread's interpreter
365          * This gives thread access to "static data" and code.
366          */
367
368         PerlIO_flush((PerlIO*)NULL);
369
370 #ifdef WIN32
371         thread->interp = perl_clone(aTHX, CLONEf_KEEP_PTR_TABLE | CLONEf_CLONE_HOST);
372 #else
373         thread->interp = perl_clone(aTHX, CLONEf_KEEP_PTR_TABLE);
374 #endif
375         /* perl_clone leaves us in new interpreter's context.
376            As it is tricky to spot implcit aTHX create a new scope
377            with aTHX matching the context for the duration of
378            our work for new interpreter.
379          */
380         {
381             dTHXa(thread->interp);
382             /* Here we remove END blocks since they should only run
383                in the thread they are created
384             */
385             SvREFCNT_dec(PL_endav);
386             PL_endav = newAV();
387             clone_param.flags = 0;
388             thread->init_function = sv_dup(init_function, &clone_param);
389             if (SvREFCNT(thread->init_function) == 0) {
390                 SvREFCNT_inc(thread->init_function);
391             }
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         }
399
400         PERL_SET_CONTEXT(aTHX);
401
402         /* Start the thread */
403
404 #ifdef WIN32
405
406         thread->handle = CreateThread(NULL, 0, Perl_ithread_run,
407                         (LPVOID)thread, 0, &thread->thr);
408
409 #else
410         {
411           static pthread_attr_t attr;
412           static int attr_inited = 0;
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
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
426 #ifdef OLD_PTHREADS_API
427           pthread_create( &thread->thr, attr, Perl_ithread_run, (void *)thread);
428 #else
429           pthread_create( &thread->thr, &attr, Perl_ithread_run, (void *)thread);
430 #endif
431         }
432 #endif
433         known_threads++;
434         active_threads++;
435         MUTEX_UNLOCK(&create_destruct_mutex);
436         return ithread_to_SV(aTHX_ obj, thread, classname, FALSE);
437 }
438
439 SV*
440 Perl_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);
445 }
446
447 /*
448  * Joins the thread this code needs to take the returnvalue from the
449  * call_sv and send it back
450  */
451
452 void
453 Perl_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   }
463 }
464
465 AV*
466 Perl_ithread_join(pTHX_ SV *obj)
467 {
468     ithread *thread = SV_to_ithread(aTHX_ obj);
469     MUTEX_LOCK(&thread->mutex);
470     if (thread->state & PERL_ITHR_DETACHED) {
471         MUTEX_UNLOCK(&thread->mutex);
472         Perl_croak(aTHX_ "Cannot join a detached thread");
473     }
474     else if (thread->state & PERL_ITHR_JOINED) {
475         MUTEX_UNLOCK(&thread->mutex);
476         Perl_croak(aTHX_ "Thread already joined");
477     }
478     else {
479         AV* retparam;
480 #ifdef WIN32
481         DWORD waitcode;
482 #else
483         void *retval;
484 #endif
485         MUTEX_UNLOCK(&thread->mutex);
486 #ifdef WIN32
487         waitcode = WaitForSingleObject(thread->handle, INFINITE);
488 #else
489         pthread_join(thread->thr,&retval);
490 #endif
491         MUTEX_LOCK(&thread->mutex);
492         
493         /* sv_dup over the args */
494         {
495           AV* params = (AV*) SvRV(thread->params);      
496           CLONE_PARAMS clone_params;
497           clone_params.stashes = newAV();
498           PL_ptr_table = ptr_table_new();
499           retparam = (AV*) sv_dup((SV*)params, &clone_params);
500           SvREFCNT_dec(clone_params.stashes);
501           SvREFCNT_inc(retparam);
502           ptr_table_free(PL_ptr_table);
503           PL_ptr_table = NULL;
504
505         }
506         /* We have finished with it */
507         thread->state |= PERL_ITHR_JOINED;
508         MUTEX_UNLOCK(&thread->mutex);
509         sv_unmagic(SvRV(obj),PERL_MAGIC_shared_scalar);
510         Perl_ithread_destruct(aTHX_ thread, "joined");
511         return retparam;
512     }
513     return (AV*)NULL;
514 }
515
516 void
517 Perl_ithread_DESTROY(pTHX_ SV *sv)
518 {
519     ithread *thread = SV_to_ithread(aTHX_ sv);
520     sv_unmagic(SvRV(sv),PERL_MAGIC_shared_scalar);
521 }
522
523 #endif /* USE_ITHREADS */
524
525 MODULE = threads                PACKAGE = threads       PREFIX = ithread_
526 PROTOTYPES: DISABLE
527
528 #ifdef USE_ITHREADS
529
530 void
531 ithread_new (classname, function_to_call, ...)
532 char *  classname
533 SV *    function_to_call
534 CODE:
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 }
546
547 void
548 ithread_self(char *classname)
549 CODE:
550 {
551         ST(0) = sv_2mortal(Perl_ithread_self(aTHX_ Nullsv,classname));
552         XSRETURN(1);
553 }
554
555 int
556 ithread_tid(ithread *thread)
557
558 void
559 ithread_join(SV *obj)
560 PPCODE:
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
571 void
572 ithread_yield(ithread *thread)
573
574 void
575 ithread_detach(ithread *thread)
576
577 void
578 ithread_DESTROY(SV *thread)
579
580 #endif /* USE_ITHREADS */
581
582 BOOT:
583 {
584 #ifdef USE_ITHREADS
585         ithread* thread;
586         PL_perl_destruct_level = 2;
587         PERL_THREAD_ALLOC_SPECIFIC(self_key);
588         MUTEX_INIT(&create_destruct_mutex);
589         MUTEX_LOCK(&create_destruct_mutex);
590         PL_threadhook = &Perl_ithread_hook;
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++;
601         known_threads++;
602         active_threads++;
603         thread->state = 1;
604 #ifdef WIN32
605         thread->thr = GetCurrentThreadId();
606 #else
607         thread->thr = pthread_self();
608 #endif
609
610         PERL_THREAD_SETSPECIFIC(self_key,thread);
611         MUTEX_UNLOCK(&create_destruct_mutex);
612 #endif /* USE_ITHREADS */
613 }
614