include/am-thread-posix.h
author David Anderson <danderson@mozilla.com>
Tue Aug 27 00:49:33 2013 -0700 (2013-08-27)
changeset 12 cebfc7eeafa5
parent 0 ba3d4abaf3f1
permissions -rw-r--r--
Added hash table tests.
     1 // vim: set sts=8 ts=2 sw=2 tw=99 et:
     2 //
     3 // Copyright (C) 2013, David Anderson and AlliedModders LLC
     4 // All rights reserved.
     5 // 
     6 // Redistribution and use in source and binary forms, with or without
     7 // modification, are permitted provided that the following conditions are met:
     8 // 
     9 //  * Redistributions of source code must retain the above copyright notice, this
    10 //    list of conditions and the following disclaimer.
    11 //  * Redistributions in binary form must reproduce the above copyright notice,
    12 //    this list of conditions and the following disclaimer in the documentation
    13 //    and/or other materials provided with the distribution.
    14 //  * Neither the name of AlliedModders LLC nor the names of its contributors
    15 //    may be used to endorse or promote products derived from this software
    16 //    without specific prior written permission.
    17 //
    18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
    19 // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
    20 // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
    21 // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
    22 // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
    23 // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
    24 // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
    25 // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
    26 // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
    27 // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
    28 // POSSIBILITY OF SUCH DAMAGE.
    29 
    30 #ifndef _include_amtl_thread_posix_h_
    31 #define _include_amtl_thread_posix_h_
    32 
    33 #include <pthread.h>
    34 #include <sys/time.h>
    35 #include <errno.h>
    36 #include <stdio.h>
    37 #if defined(__linux__)
    38 # include <sys/prctl.h>
    39 #endif
    40 #if defined(__APPLE__)
    41 # include <dlfcn.h>
    42 #endif
    43 
    44 namespace ke {
    45 
    46 class Mutex : public Lockable
    47 {
    48  public:
    49   Mutex() {
    50 #if !defined(NDEBUG)
    51     int rv =
    52 #endif
    53       pthread_mutex_init(&mutex_, NULL);
    54     assert(rv == 0);
    55   }
    56   ~Mutex() {
    57     pthread_mutex_destroy(&mutex_);
    58   }
    59 
    60   bool DoTryLock() KE_OVERRIDE {
    61     return pthread_mutex_trylock(&mutex_) == 0;
    62   }
    63 
    64   void DoLock() KE_OVERRIDE {
    65     pthread_mutex_lock(&mutex_);
    66   }
    67 
    68   void DoUnlock() KE_OVERRIDE {
    69     pthread_mutex_unlock(&mutex_);
    70   }
    71   
    72   pthread_mutex_t *raw() {
    73     return &mutex_;
    74   }
    75 
    76  private:
    77   pthread_mutex_t mutex_;
    78 };
    79 
    80 // Currently, this class only supports single-listener CVs.
    81 class ConditionVariable : public Lockable
    82 {
    83  public:
    84   ConditionVariable() {
    85 #if !defined(NDEBUG)
    86     int rv =
    87 #endif
    88       pthread_cond_init(&cv_, NULL);
    89     assert(rv == 0);
    90   }
    91   ~ConditionVariable() {
    92     pthread_cond_destroy(&cv_);
    93   }
    94 
    95   bool DoTryLock() KE_OVERRIDE {
    96     return mutex_.DoTryLock();
    97   }
    98   void DoLock() KE_OVERRIDE {
    99     mutex_.DoLock();
   100   }
   101   void DoUnlock() KE_OVERRIDE {
   102     mutex_.DoUnlock();
   103   }
   104 
   105   void Notify() {
   106     AssertCurrentThreadOwns();
   107     pthread_cond_signal(&cv_);
   108   }
   109 
   110   WaitResult Wait(size_t timeout_ms) {
   111     AssertCurrentThreadOwns();
   112 
   113 #if defined(__linux__)
   114     struct timespec ts;
   115     if (clock_gettime(CLOCK_REALTIME, &ts) == -1)
   116       return Wait_Error;
   117 #else
   118     struct timeval tv;
   119     gettimeofday(&tv, NULL);
   120 
   121     struct timespec ts;
   122     ts.tv_sec = tv.tv_sec;
   123     ts.tv_nsec = tv.tv_usec * 1000;
   124 #endif
   125 
   126     ts.tv_sec += timeout_ms / 1000;
   127     ts.tv_nsec += (timeout_ms % 1000) * 1000000;
   128     if (ts.tv_nsec >= 1000000000) {
   129       ts.tv_sec++;
   130       ts.tv_nsec -= 1000000000;
   131     }
   132 
   133     DebugSetUnlocked();
   134     int rv = pthread_cond_timedwait(&cv_, mutex_.raw(), &ts);
   135     DebugSetLocked();
   136 
   137     if (rv == ETIMEDOUT)
   138       return Wait_Timeout;
   139     if (rv == 0)
   140       return Wait_Signaled;
   141     return Wait_Error;
   142   }
   143 
   144   WaitResult Wait() {
   145     AssertCurrentThreadOwns();
   146 
   147     DebugSetUnlocked();
   148     int rv = pthread_cond_wait(&cv_, mutex_.raw());
   149     DebugSetLocked();
   150 
   151     if (rv == 0)
   152       return Wait_Signaled;
   153     return Wait_Error;
   154   }
   155 
   156  private:
   157   Mutex mutex_;
   158   pthread_cond_t cv_;
   159 };
   160 
   161 class Thread
   162 {
   163   struct ThreadData {
   164     IRunnable *run;
   165     char name[17];
   166   };
   167  public:
   168   Thread(IRunnable *run, const char *name = NULL) {
   169     ThreadData *data = new ThreadData;
   170     data->run = run;
   171     snprintf(data->name, sizeof(data->name), "%s", name ? name : "");
   172 
   173     initialized_ = (pthread_create(&thread_, NULL, Main, data) == 0);
   174     if (!initialized_)
   175       delete data;
   176   }
   177 
   178   bool Succeeded() const {
   179     return initialized_;
   180   }
   181 
   182   void Join() {
   183     if (!Succeeded())
   184       return;
   185     pthread_join(thread_, NULL);
   186   }
   187 
   188  private:
   189   static void *Main(void *arg) {
   190     AutoPtr<ThreadData> data((ThreadData *)arg);
   191 
   192     if (data->name[0]) {
   193 #if defined(__linux__)
   194       prctl(PR_SET_NAME, (unsigned long)data->name);
   195 #elif defined(__APPLE__)
   196       int (*fn)(const char *) = (int (*)(const char *))dlsym(RTLD_DEFAULT, "pthread_setname_np");
   197       if (fn)
   198         fn(data->name);
   199 #endif
   200     }
   201     data->run->Run();
   202     return NULL;
   203   }
   204 
   205  private:
   206   bool initialized_;
   207   pthread_t thread_;
   208 };
   209 
   210 } // namespace ke
   211 
   212 #endif // _include_amtl_thread_posix_h_
   213