GraphLab: Distributed Graph-Parallel API  2.1
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
mutex.hpp
1 /**
2  * Copyright (c) 2009 Carnegie Mellon University.
3  * All rights reserved.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing,
12  * software distributed under the License is distributed on an "AS
13  * IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
14  * express or implied. See the License for the specific language
15  * governing permissions and limitations under the License.
16  *
17  * For more about this software visit:
18  *
19  * http://www.graphlab.ml.cmu.edu
20  *
21  */
22 
23 #ifndef GRAPHLAB_MUTEX_HPP
24 #define GRAPHLAB_MUTEX_HPP
25 
26 
27 #include <pthread.h>
28 #include <graphlab/logger/assertions.hpp>
29 
30 
31 namespace graphlab {
32 
33  /**
34  * \ingroup util
35  *
36  * Simple wrapper around pthread's mutex.
37  * Before you use, see \ref parallel_object_intricacies.
38  */
39  class mutex {
40  private:
41  // mutable not actually needed
42  mutable pthread_mutex_t m_mut;
43  public:
44  /// constructs a mutex
45  mutex() {
46  int error = pthread_mutex_init(&m_mut, NULL);
47  ASSERT_TRUE(!error);
48  }
49  /** Copy constructor which does not copy. Do not use!
50  Required for compatibility with some STL implementations (LLVM).
51  which use the copy constructor for vector resize,
52  rather than the standard constructor. */
53  mutex(const mutex&) {
54  int error = pthread_mutex_init(&m_mut, NULL);
55  ASSERT_TRUE(!error);
56  }
57 
58  ~mutex(){
59  int error = pthread_mutex_destroy( &m_mut );
60  ASSERT_TRUE(!error);
61  }
62 
63  // not copyable
64  void operator=(const mutex& m) { }
65 
66  /// Acquires a lock on the mutex
67  inline void lock() const {
68  int error = pthread_mutex_lock( &m_mut );
69  // if (error) std::cout << "mutex.lock() error: " << error << std::endl;
70  ASSERT_TRUE(!error);
71  }
72  /// Releases a lock on the mutex
73  inline void unlock() const {
74  int error = pthread_mutex_unlock( &m_mut );
75  ASSERT_TRUE(!error);
76  }
77  /// Non-blocking attempt to acquire a lock on the mutex
78  inline bool try_lock() const {
79  return pthread_mutex_trylock( &m_mut ) == 0;
80  }
81  friend class conditional;
82  }; // End of Mutex
83 
84 
85 } // end of graphlab namespace
86 
87 
88 #endif