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