00001 // this is for emacs file handling -*- mode: c++; indent-tabs-mode: nil -*- 00002 00003 // -- BEGIN LICENSE BLOCK ---------------------------------------------- 00004 // This file is part of FZIs ic_workspace. 00005 // 00006 // This program is free software licensed under the LGPL 00007 // (GNU LESSER GENERAL PUBLIC LICENSE Version 3). 00008 // You can find a copy of this license in LICENSE folder in the top 00009 // directory of the source code. 00010 // 00011 // © Copyright 2016 FZI Forschungszentrum Informatik, Karlsruhe, Germany 00012 // 00013 // -- END LICENSE BLOCK ------------------------------------------------ 00014 00015 //---------------------------------------------------------------------- 00022 //---------------------------------------------------------------------- 00023 #include "icl_core_thread/MutexImplPosix.h" 00024 00025 #include <pthread.h> 00026 #include <icl_core/os_time.h> 00027 00028 #include "icl_core_thread/Common.h" 00029 00030 namespace icl_core { 00031 namespace thread { 00032 00033 MutexImplPosix::MutexImplPosix() 00034 : m_mutex(NULL) 00035 { 00036 m_mutex = new pthread_mutex_t; 00037 pthread_mutexattr_t mutex_attr; 00038 pthread_mutexattr_init(&mutex_attr); 00039 pthread_mutexattr_settype(&mutex_attr, PTHREAD_MUTEX_RECURSIVE); 00040 pthread_mutex_init(m_mutex, &mutex_attr); 00041 pthread_mutexattr_destroy(&mutex_attr); 00042 } 00043 00044 MutexImplPosix::~MutexImplPosix() 00045 { 00046 if (m_mutex) 00047 { 00048 pthread_mutex_destroy(m_mutex); 00049 delete m_mutex; 00050 m_mutex = NULL; 00051 } 00052 } 00053 00054 bool MutexImplPosix::lock() 00055 { 00056 return pthread_mutex_lock(m_mutex) == 0; 00057 } 00058 00059 bool MutexImplPosix::lock(const ::icl_core::TimeStamp& timeout) 00060 { 00061 #ifdef _SYSTEM_DARWIN_ 00062 int ret = pthread_mutex_trylock(m_mutex); 00063 while ((ret != 0) && ((timeout > icl_core::TimeStamp::now()))) 00064 { 00065 // one microsecond 00066 icl_core::os::usleep(1); 00067 ret = pthread_mutex_trylock(m_mutex); 00068 } 00069 return ret == 0; 00070 #else 00071 struct timespec timeout_spec = timeout.timespec(); 00072 int ret = pthread_mutex_timedlock(m_mutex, &timeout_spec); 00073 return (ret == 0); 00074 #endif 00075 } 00076 00077 bool MutexImplPosix::lock(const ::icl_core::TimeSpan& timeout) 00078 { 00079 return lock(impl::getAbsoluteTimeout(timeout)); 00080 } 00081 00082 bool MutexImplPosix::tryLock() 00083 { 00084 int ret = pthread_mutex_trylock(m_mutex); 00085 return (ret == 0); 00086 } 00087 00088 void MutexImplPosix::unlock() 00089 { 00090 pthread_mutex_unlock(m_mutex); 00091 } 00092 00093 } 00094 }