Debian Codegraph @

rpython/translator/c/src/thread_pthread.c

raw symbols SCIP
1
2 /* Posix threads interface (from CPython) */
3
4 #include <unistd.h> /* for the _POSIX_xxx and _POSIX_THREAD_xxx defines */
5 #include <stdlib.h>
6 #include <pthread.h>
7 #include <signal.h>
8 #include <stdio.h>
9 #include <errno.h>
10 #include <assert.h>
11 #include <sys/time.h>
12
13 #if defined(__linux__)
14 # include <sys/syscall.h> /* syscall(SYS_gettid) */
15 #elif defined(__FreeBSD__)
16 # include <pthread_np.h> /* pthread_getthreadid_np() */
17 #elif defined(__OpenBSD__)
18 # include <unistd.h> /* getthrid() */
19 #elif defined(_AIX)
20 # include <sys/thread.h> /* thread_self() */
21 #elif defined(__NetBSD__)
22 # include <lwp.h> /* _lwp_self() */
23 #endif
24
25
26 /* The following is hopefully equivalent to what CPython does
27 (which is trying to compile a snippet of code using it) */
28 #ifdef PTHREAD_SCOPE_SYSTEM
29 # ifndef PTHREAD_SYSTEM_SCHED_SUPPORTED
30 # define PTHREAD_SYSTEM_SCHED_SUPPORTED
31 # endif
32 #endif
33
34 #if !defined(pthread_attr_default)
35 # define pthread_attr_default ((pthread_attr_t *)NULL)
36 #endif
37 #if !defined(pthread_mutexattr_default)
38 # define pthread_mutexattr_default ((pthread_mutexattr_t *)NULL)
39 #endif
40 #if !defined(pthread_condattr_default)
41 # define pthread_condattr_default ((pthread_condattr_t *)NULL)
42 #endif
43
44 #define CHECK_STATUS(name) if (status != 0) { perror(name); error = 1; }
45
46 /* The POSIX spec requires that use of pthread_attr_setstacksize
47 be conditional on _POSIX_THREAD_ATTR_STACKSIZE being defined. */
48 #ifdef _POSIX_THREAD_ATTR_STACKSIZE
49 # ifndef THREAD_STACK_SIZE
50 # define THREAD_STACK_SIZE 0 /* use default stack size */
51 # endif
52
53 # if (defined(__APPLE__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__)) && defined(THREAD_STACK_SIZE) && THREAD_STACK_SIZE == 0
54 /* The default stack size for new threads on OSX is small enough that
55 * we'll get hard crashes instead of 'maximum recursion depth exceeded'
56 * exceptions.
57 *
58 * The default stack size below is the minimal stack size where a
59 * simple recursive function doesn't cause a hard crash.
60 */
61 # undef THREAD_STACK_SIZE
62 # define THREAD_STACK_SIZE 0x400000
63 # endif
64 /* for safety, ensure a viable minimum stacksize */
65 # define THREAD_STACK_MIN 0x8000 /* 32kB */
66 #else /* !_POSIX_THREAD_ATTR_STACKSIZE */
67 # ifdef THREAD_STACK_SIZE
68 # error "THREAD_STACK_SIZE defined but _POSIX_THREAD_ATTR_STACKSIZE undefined"
69 # endif
70 #endif
71
72 static long _pypythread_stacksize = 0;
73
74 Signed RPyThreadStart(void (*func)(void))
75 {
76 /* a kind-of-invalid cast, but the 'func' passed here doesn't expect
77 any argument, so it's unlikely to cause problems */
78 return RPyThreadStartEx((void(*)(void *))func, NULL);
79 }
80
81 Signed RPyThreadStartEx(void (*func)(void *), void *arg)
82 {
83 pthread_t th;
84 int status;
85 #if defined(THREAD_STACK_SIZE) || defined(PTHREAD_SYSTEM_SCHED_SUPPORTED)
86 pthread_attr_t attrs;
87 #endif
88 #if defined(THREAD_STACK_SIZE)
89 size_t tss;
90 #endif
91
92 #if defined(THREAD_STACK_SIZE) || defined(PTHREAD_SYSTEM_SCHED_SUPPORTED)
93 pthread_attr_init(&attrs);
94 #endif
95 #ifdef THREAD_STACK_SIZE
96 tss = (_pypythread_stacksize != 0) ? _pypythread_stacksize
97 : THREAD_STACK_SIZE;
98 if (tss != 0)
99 pthread_attr_setstacksize(&attrs, tss);
100 #endif
101 #if defined(PTHREAD_SYSTEM_SCHED_SUPPORTED) && !(defined(__FreeBSD__) || defined(__FreeBSD_kernel__))
102 pthread_attr_setscope(&attrs, PTHREAD_SCOPE_SYSTEM);
103 #endif
104
105 status = pthread_create(&th,
106 #if defined(THREAD_STACK_SIZE) || defined(PTHREAD_SYSTEM_SCHED_SUPPORTED)
107 &attrs,
108 #else
109 (pthread_attr_t*)NULL,
110 #endif
111 /* the next line does an invalid cast: pthread_create() will see a
112 function that returns random garbage. The code is the same as
113 CPython: this random garbage will be stored for pthread_join()
114 to return, but in this case pthread_join() is never called. */
115 (void* (*)(void *))func,
116 (void *)arg
117 );
118
119 #if defined(THREAD_STACK_SIZE) || defined(PTHREAD_SYSTEM_SCHED_SUPPORTED)
120 pthread_attr_destroy(&attrs);
121 #endif
122 if (status != 0)
123 return -1;
124
125 pthread_detach(th);
126
127 #ifdef __CYGWIN__
128 /* typedef __uint32_t pthread_t; */
129 return (Signed) th;
130 #else
131 if (sizeof(pthread_t) <= sizeof(Signed))
132 return (Signed) th;
133 else
134 return (Signed) *(Signed *) &th;
135 #endif
136 }
137
138 Signed RPyThreadGetStackSize(void)
139 {
140 return _pypythread_stacksize;
141 }
142
143 Signed RPyThreadSetStackSize(Signed newsize)
144 {
145 #if defined(THREAD_STACK_SIZE)
146 pthread_attr_t attrs;
147 size_t tss_min;
148 int rc;
149 #endif
150
151 if (newsize == 0) { /* set to default */
152 _pypythread_stacksize = 0;
153 return 0;
154 }
155
156 #if defined(THREAD_STACK_SIZE)
157 # if defined(PTHREAD_STACK_MIN)
158 tss_min = PTHREAD_STACK_MIN > THREAD_STACK_MIN ? PTHREAD_STACK_MIN
159 : THREAD_STACK_MIN;
160 # else
161 tss_min = THREAD_STACK_MIN;
162 # endif
163 if (newsize >= tss_min) {
164 /* validate stack size by setting thread attribute */
165 if (pthread_attr_init(&attrs) == 0) {
166 rc = pthread_attr_setstacksize(&attrs, newsize);
167 pthread_attr_destroy(&attrs);
168 if (rc == 0) {
169 _pypythread_stacksize = newsize;
170 return 0;
171 }
172 }
173 }
174 return -1;
175 #else
176 return -2;
177 #endif
178 }
179
180 #ifdef GETTIMEOFDAY_NO_TZ
181 #define RPY_GETTIMEOFDAY(ptv) gettimeofday(ptv)
182 #else
183 #define RPY_GETTIMEOFDAY(ptv) gettimeofday(ptv, (struct timezone *)NULL)
184 #endif
185
186 #define RPY_MICROSECONDS_TO_TIMESPEC(microseconds, ts) \
187 do { \
188 struct timeval tv; \
189 RPY_GETTIMEOFDAY(&tv); \
190 tv.tv_usec += microseconds % 1000000; \
191 tv.tv_sec += microseconds / 1000000; \
192 tv.tv_sec += tv.tv_usec / 1000000; \
193 tv.tv_usec %= 1000000; \
194 ts.tv_sec = tv.tv_sec; \
195 ts.tv_nsec = tv.tv_usec * 1000; \
196 } while(0)
197
198 int RPyThreadAcquireLock(struct RPyOpaque_ThreadLock *lock, int waitflag)
199 {
200 return RPyThreadAcquireLockTimed(lock, waitflag ? -1 : 0, /*intr_flag=*/0);
201 }
202
203 unsigned long
204 RPyThread_get_thread_native_id(void)
205 {
206 #ifdef __APPLE__
207 uint64_t native_id;
208 (void) pthread_threadid_np(NULL, &native_id);
209 #elif defined(__linux__)
210 pid_t native_id;
211 native_id = syscall(SYS_gettid);
212 #elif defined(__FreeBSD__)
213 int native_id;
214 native_id = pthread_getthreadid_np();
215 #elif defined(__OpenBSD__)
216 pid_t native_id;
217 native_id = getthrid();
218 #elif defined(_AIX)
219 tid_t native_id;
220 native_id = thread_self();
221 #elif defined(__NetBSD__)
222 lwpid_t native_id;
223 native_id = _lwp_self();
224 #endif
225 return (unsigned long) native_id;
226 }
227
228 int
229 RPyThread_kill(Signed id, int signal)
230 {
231 return pthread_kill((pthread_t)id, signal);
232 }
233
234 /************************************************************/
235 #ifdef USE_SEMAPHORES
236 /************************************************************/
237
238 #include <semaphore.h>
239
240 void RPyThreadAfterFork(void)
241 {
242 }
243
244 int RPyThreadLockInit(struct RPyOpaque_ThreadLock *lock)
245 {
246 int status, error = 0;
247 lock->initialized = 0;
248 status = sem_init(&lock->sem, 0, 1);
249 CHECK_STATUS("sem_init");
250 if (error)
251 return 0;
252 lock->initialized = 1;
253 return 1;
254 }
255
256 void RPyOpaqueDealloc_ThreadLock(struct RPyOpaque_ThreadLock *lock)
257 {
258 int status, error = 0;
259 if (lock->initialized) {
260 status = sem_destroy(&lock->sem);
261 CHECK_STATUS("sem_destroy");
262 /* 'error' is ignored;
263 CHECK_STATUS already printed an error message */
264 }
265 }
266
267 /*
268 * As of February 2002, Cygwin thread implementations mistakenly report error
269 * codes in the return value of the sem_ calls (like the pthread_ functions).
270 * Correct implementations return -1 and put the code in errno. This supports
271 * either.
272 */
273 static int
274 rpythread_fix_status(int status)
275 {
276 return (status == -1) ? errno : status;
277 }
278
279 RPyLockStatus
280 RPyThreadAcquireLockTimed(struct RPyOpaque_ThreadLock *lock,
281 RPY_TIMEOUT_T microseconds, int intr_flag)
282 {
283 RPyLockStatus success;
284 sem_t *thelock = &lock->sem;
285 int status, error = 0;
286 struct timespec ts;
287
288 if (microseconds > 0)
289 RPY_MICROSECONDS_TO_TIMESPEC(microseconds, ts);
290 do {
291 if (microseconds > 0)
292 status = rpythread_fix_status(sem_timedwait(thelock, &ts));
293 else if (microseconds == 0)
294 status = rpythread_fix_status(sem_trywait(thelock));
295 else
296 status = rpythread_fix_status(sem_wait(thelock));
297 /* Retry if interrupted by a signal, unless the caller wants to be
298 notified. */
299 } while (!intr_flag && status == EINTR);
300
301 /* Don't check the status if we're stopping because of an interrupt. */
302 if (!(intr_flag && status == EINTR)) {
303 if (microseconds > 0) {
304 if (status != ETIMEDOUT)
305 CHECK_STATUS("sem_timedwait");
306 }
307 else if (microseconds == 0) {
308 if (status != EAGAIN)
309 CHECK_STATUS("sem_trywait");
310 }
311 else {
312 CHECK_STATUS("sem_wait");
313 }
314 }
315
316 if (status == 0) {
317 success = RPY_LOCK_ACQUIRED;
318 } else if (intr_flag && status == EINTR) {
319 success = RPY_LOCK_INTR;
320 } else {
321 success = RPY_LOCK_FAILURE;
322 }
323 return success;
324 }
325
326 Signed RPyThreadReleaseLock(struct RPyOpaque_ThreadLock *lock)
327 {
328 sem_t *thelock = &lock->sem;
329 int status, error = 0;
330 int current_value;
331
332 /* If the current value is > 0, then the lock is not acquired so far.
333 Oops. */
334 sem_getvalue(thelock, &current_value);
335 if (current_value > 0) {
336 return -1;
337 }
338
339 status = sem_post(thelock);
340 CHECK_STATUS("sem_post");
341
342 return 0;
343 }
344
345 /************************************************************/
346 #else /* no semaphores */
347 /************************************************************/
348
349 struct RPyOpaque_ThreadLock *alllocks; /* doubly-linked list */
350
351 void RPyThreadAfterFork(void)
352 {
353 /* Mess. We have no clue about how it works on CPython on OSX,
354 but the issue is that the state of mutexes is not really
355 preserved across a fork(). So we need to walk over all lock
356 objects here, and rebuild their mutex and condition variable.
357
358 See e.g. http://hackage.haskell.org/trac/ghc/ticket/1391 for
359 a similar bug about GHC.
360 */
361 struct RPyOpaque_ThreadLock *p = alllocks;
362 alllocks = NULL;
363 while (p) {
364 struct RPyOpaque_ThreadLock *next = p->next;
365 int was_locked = p->locked;
366 RPyThreadLockInit(p);
367 p->locked = was_locked;
368 p = next;
369 }
370 /* Also reinitialize the 'mutex_gil' mutexes, and resets the
371 number of other waiting threads to zero. */
372 RPyGilAllocate();
373 }
374
375 int RPyThreadLockInit(struct RPyOpaque_ThreadLock *lock)
376 {
377 int status, error = 0;
378
379 lock->initialized = 0;
380 lock->locked = 0;
381
382 status = pthread_mutex_init(&lock->mut,
383 pthread_mutexattr_default);
384 CHECK_STATUS("pthread_mutex_init");
385
386 status = pthread_cond_init(&lock->lock_released,
387 pthread_condattr_default);
388 CHECK_STATUS("pthread_cond_init");
389
390 if (error)
391 return 0;
392 lock->initialized = 1;
393 /* add 'lock' in the doubly-linked list */
394 if (alllocks)
395 alllocks->prev = lock;
396 lock->next = alllocks;
397 lock->prev = NULL;
398 alllocks = lock;
399 return 1;
400 }
401
402 void RPyOpaqueDealloc_ThreadLock(struct RPyOpaque_ThreadLock *lock)
403 {
404 int status, error = 0;
405 if (lock->initialized) {
406 /* remove 'lock' from the doubly-linked list */
407 if (lock->prev)
408 lock->prev->next = lock->next;
409 else {
410 assert(alllocks == lock);
411 alllocks = lock->next;
412 }
413 if (lock->next)
414 lock->next->prev = lock->prev;
415
416 status = pthread_cond_destroy(&lock->lock_released);
417 CHECK_STATUS("pthread_cond_destroy");
418
419 status = pthread_mutex_destroy(&lock->mut);
420 CHECK_STATUS("pthread_mutex_destroy");
421
422 /* 'error' is ignored;
423 CHECK_STATUS already printed an error message */
424 }
425 }
426
427 RPyLockStatus
428 RPyThreadAcquireLockTimed(struct RPyOpaque_ThreadLock *lock,
429 RPY_TIMEOUT_T microseconds, int intr_flag)
430 {
431 RPyLockStatus success;
432 int status, error = 0;
433
434 status = pthread_mutex_lock( &lock->mut );
435 CHECK_STATUS("pthread_mutex_lock[1]");
436
437 if (lock->locked == 0) {
438 success = RPY_LOCK_ACQUIRED;
439 } else if (microseconds == 0) {
440 success = RPY_LOCK_FAILURE;
441 } else {
442 struct timespec ts;
443 if (microseconds > 0)
444 RPY_MICROSECONDS_TO_TIMESPEC(microseconds, ts);
445 /* continue trying until we get the lock */
446
447 /* mut must be locked by me -- part of the condition
448 * protocol */
449 success = RPY_LOCK_FAILURE;
450 while (success == RPY_LOCK_FAILURE) {
451 if (microseconds > 0) {
452 status = pthread_cond_timedwait(
453 &lock->lock_released,
454 &lock->mut, &ts);
455 if (status == ETIMEDOUT)
456 break;
457 CHECK_STATUS("pthread_cond_timed_wait");
458 }
459 else {
460 status = pthread_cond_wait(
461 &lock->lock_released,
462 &lock->mut);
463 CHECK_STATUS("pthread_cond_wait");
464 }
465
466 if (intr_flag && status == 0 && lock->locked) {
467 /* We were woken up, but didn't get the lock. We probably received
468 * a signal. Return RPY_LOCK_INTR to allow the caller to handle
469 * it and retry. */
470 success = RPY_LOCK_INTR;
471 break;
472 } else if (status == 0 && !lock->locked) {
473 success = RPY_LOCK_ACQUIRED;
474 } else {
475 success = RPY_LOCK_FAILURE;
476 }
477 }
478 }
479 if (success == RPY_LOCK_ACQUIRED) lock->locked = 1;
480 status = pthread_mutex_unlock( &lock->mut );
481 CHECK_STATUS("pthread_mutex_unlock[1]");
482
483 if (error) success = RPY_LOCK_FAILURE;
484 return success;
485 }
486
487 Signed RPyThreadReleaseLock(struct RPyOpaque_ThreadLock *lock)
488 {
489 int status, error = 0;
490 Signed result;
491
492 status = pthread_mutex_lock( &lock->mut );
493 CHECK_STATUS("pthread_mutex_lock[3]");
494
495 /* If the lock was non-locked, then oops, we return -1 for failure.
496 Otherwise, we return 0 for success. */
497 result = (lock->locked == 0) ? -1 : 0;
498
499 lock->locked = 0;
500
501 /* wake up someone (anyone, if any) waiting on the lock */
502 status = pthread_cond_signal( &lock->lock_released );
503 CHECK_STATUS("pthread_cond_signal");
504
505 status = pthread_mutex_unlock( &lock->mut );
506 CHECK_STATUS("pthread_mutex_unlock[3]");
507
508 return result;
509 }
510
511 /************************************************************/
512 #endif /* no semaphores */
513 /************************************************************/
514
515
516 /************************************************************/
517 /* GIL code */
518 /************************************************************/
519
520 #include <time.h>
521
522 #define ASSERT_STATUS(call) \
523 if (call != 0) { \
524 perror("Fatal error: " #call); \
525 abort(); \
526 }
527
528 static inline void timespec_delay(struct timespec *t, double incr)
529 {
530 #ifdef CLOCK_REALTIME
531 clock_gettime(CLOCK_REALTIME, t);
532 #else
533 struct timeval tv;
534 RPY_GETTIMEOFDAY(&tv);
535 t->tv_sec = tv.tv_sec;
536 t->tv_nsec = tv.tv_usec * 1000 + 999;
537 #endif
538 /* assumes that "incr" is not too large, less than 1 second */
539 long nsec = t->tv_nsec + (long)(incr * 1000000000.0);
540 if (nsec >= 1000000000) {
541 t->tv_sec += 1;
542 nsec -= 1000000000;
543 assert(nsec < 1000000000);
544 }
545 t->tv_nsec = nsec;
546 }
547
548 typedef pthread_mutex_t mutex1_t;
549
550 static inline void mutex1_init(mutex1_t *mutex) {
551 ASSERT_STATUS(pthread_mutex_init(mutex, pthread_mutexattr_default));
552 }
553 static inline void mutex1_lock(mutex1_t *mutex) {
554 ASSERT_STATUS(pthread_mutex_lock(mutex));
555 }
556 static inline void mutex1_unlock(mutex1_t *mutex) {
557 ASSERT_STATUS(pthread_mutex_unlock(mutex));
558 }
559
560 typedef struct {
561 char locked;
562 pthread_mutex_t mut;
563 pthread_cond_t cond;
564 } mutex2_t;
565
566 static inline void mutex2_init_locked(mutex2_t *mutex) {
567 mutex->locked = 1;
568 ASSERT_STATUS(pthread_mutex_init(&mutex->mut, pthread_mutexattr_default));
569 ASSERT_STATUS(pthread_cond_init(&mutex->cond, pthread_condattr_default));
570 }
571 static inline void mutex2_unlock(mutex2_t *mutex) {
572 ASSERT_STATUS(pthread_mutex_lock(&mutex->mut));
573 mutex->locked = 0;
574 ASSERT_STATUS(pthread_mutex_unlock(&mutex->mut));
575 ASSERT_STATUS(pthread_cond_signal(&mutex->cond));
576 }
577 static inline void mutex2_loop_start(mutex2_t *mutex) {
578 ASSERT_STATUS(pthread_mutex_lock(&mutex->mut));
579 }
580 static inline void mutex2_loop_stop(mutex2_t *mutex) {
581 ASSERT_STATUS(pthread_mutex_unlock(&mutex->mut));
582 }
583 static inline int mutex2_lock_timeout(mutex2_t *mutex, double delay) {
584 if (mutex->locked) {
585 struct timespec t;
586 timespec_delay(&t, delay);
587 int error_from_timedwait = pthread_cond_timedwait(
588 &mutex->cond, &mutex->mut, &t);
589 if (error_from_timedwait != ETIMEDOUT) {
590 ASSERT_STATUS(error_from_timedwait);
591 }
592 }
593 int result = !mutex->locked;
594 mutex->locked = 1;
595 return result;
596 }
597
598 //#define pypy_lock_test_and_set(ptr, value) see thread_pthread.h
599 #define atomic_increment(ptr) __sync_add_and_fetch(ptr, 1)
600 #define atomic_decrement(ptr) __sync_sub_and_fetch(ptr, 1)
601 #define RPy_CompilerMemoryBarrier() asm("":::"memory")
602 #define HAVE_PTHREAD_ATFORK 1
603
604 #include "src/asm.h" /* for RPy_YieldProcessor() */
605 #ifndef RPy_YieldProcessor
606 # define RPy_YieldProcessor() /* nothing */
607 #endif
608
609 #include "src/thread_gil.c"