epoger@google.com | ec3ed6a | 2011-07-28 14:26:00 +0000 | [diff] [blame^] | 1 | |
| 2 | /* |
| 3 | * Copyright 2011 Google Inc. |
| 4 | * |
| 5 | * Use of this source code is governed by a BSD-style license that can be |
| 6 | * found in the LICENSE file. |
| 7 | */ |
reed@android.com | 8a1c16f | 2008-12-17 15:59:43 +0000 | [diff] [blame] | 8 | #include "SkThread.h" |
| 9 | |
| 10 | #include <pthread.h> |
| 11 | #include <errno.h> |
| 12 | |
| 13 | SkMutex gAtomicMutex; |
| 14 | |
| 15 | int32_t sk_atomic_inc(int32_t* addr) |
| 16 | { |
| 17 | SkAutoMutexAcquire ac(gAtomicMutex); |
| 18 | |
| 19 | int32_t value = *addr; |
| 20 | *addr = value + 1; |
| 21 | return value; |
| 22 | } |
| 23 | |
| 24 | int32_t sk_atomic_dec(int32_t* addr) |
| 25 | { |
| 26 | SkAutoMutexAcquire ac(gAtomicMutex); |
| 27 | |
| 28 | int32_t value = *addr; |
| 29 | *addr = value - 1; |
| 30 | return value; |
| 31 | } |
| 32 | |
| 33 | ////////////////////////////////////////////////////////////////////////////// |
| 34 | |
| 35 | static void print_pthread_error(int status) |
| 36 | { |
| 37 | switch (status) { |
| 38 | case 0: // success |
| 39 | break; |
| 40 | case EINVAL: |
| 41 | printf("pthread error [%d] EINVAL\n", status); |
| 42 | break; |
| 43 | case EBUSY: |
| 44 | printf("pthread error [%d] EBUSY\n", status); |
| 45 | break; |
| 46 | default: |
| 47 | printf("pthread error [%d] unknown\n", status); |
| 48 | break; |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | SkMutex::SkMutex(bool isGlobal) : fIsGlobal(isGlobal) |
| 53 | { |
| 54 | if (sizeof(pthread_mutex_t) > sizeof(fStorage)) |
| 55 | { |
| 56 | SkDEBUGF(("pthread mutex size = %d\n", sizeof(pthread_mutex_t))); |
| 57 | SkASSERT(!"mutex storage is too small"); |
| 58 | } |
| 59 | |
| 60 | int status; |
| 61 | pthread_mutexattr_t attr; |
| 62 | |
| 63 | status = pthread_mutexattr_init(&attr); |
| 64 | print_pthread_error(status); |
| 65 | SkASSERT(0 == status); |
| 66 | |
| 67 | status = pthread_mutex_init((pthread_mutex_t*)fStorage, &attr); |
| 68 | print_pthread_error(status); |
| 69 | SkASSERT(0 == status); |
| 70 | } |
| 71 | |
| 72 | SkMutex::~SkMutex() |
| 73 | { |
| 74 | int status = pthread_mutex_destroy((pthread_mutex_t*)fStorage); |
| 75 | |
| 76 | // only report errors on non-global mutexes |
| 77 | if (!fIsGlobal) |
| 78 | { |
| 79 | print_pthread_error(status); |
| 80 | SkASSERT(0 == status); |
| 81 | } |
| 82 | } |
| 83 | |
| 84 | void SkMutex::acquire() |
| 85 | { |
| 86 | int status = pthread_mutex_lock((pthread_mutex_t*)fStorage); |
| 87 | print_pthread_error(status); |
| 88 | SkASSERT(0 == status); |
| 89 | } |
| 90 | |
| 91 | void SkMutex::release() |
| 92 | { |
| 93 | int status = pthread_mutex_unlock((pthread_mutex_t*)fStorage); |
| 94 | print_pthread_error(status); |
| 95 | SkASSERT(0 == status); |
| 96 | } |
| 97 | |