ONPOSIX  2.0
 All Classes Namespaces Files Functions Variables Enumerator Friends Macros Pages
PosixMutex.cpp
Go to the documentation of this file.
1 /*
2  * PosixMutex.cpp
3  *
4  * Copyright (C) 2012 Evidence Srl - www.evidence.eu.com
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Library General Public
8  * License as published by the Free Software Foundation; either
9  * version 2 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14  * Library General Public License for more details.
15  *
16  * You should have received a copy of the GNU Library General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19  */
20 
21 #include "PosixMutex.hpp"
22 #include "Assert.hpp"
23 #include <errno.h>
24 #include <string.h>
25 #include <stdexcept>
26 
27 namespace onposix {
28 
29 /**
30  * \brief Constructor. Initialize the mutex.
31  *
32  * @exception runtime_error if the mutex initialization fails.
33  */
35 {
36  if (pthread_mutex_init(&mutex_, NULL) != 0)
37  throw std::runtime_error(std::string("Error: ") + strerror(errno));
38 }
39 
40 /**
41  * \brief Destructor. Destroys the mutex.
42  */
44 {
45  VERIFY_ASSERTION(!pthread_mutex_destroy(&mutex_));
46 }
47 
48 /**
49  * \brief Tries to acquire the lock.
50  *
51  * If the mutex is busy the calling thread
52  * continues its executions
53  * @return True if the lock is acquired, false otherwise.
54  */
56 {
57  if (pthread_mutex_trylock(&mutex_) == EBUSY)
58  return false;
59  else
60  return true;
61 }
62 
63 } /* onposix */