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