Lock abstraction, introduced with a view toward making the JIT thread-safe.
[oota-llvm.git] / include / Support / ThreadSupport-PThreads.h
1 //===-- Support/Lock.h - Platform-agnostic mutual exclusion -----*- C++ -*-===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains classes that implement locks (mutual exclusion
11 // variables) in a platform-agnostic way. Basically the user should
12 // just call Lock::create() to get a Lock object of the correct sort
13 // for the current platform, and use its acquire() and release()
14 // methods, or a LockHolder, to protect critical sections of code for
15 // thread-safety.
16 //
17 //===----------------------------------------------------------------------===//
18
19 #ifndef SUPPORT_LOCK_H
20 #define SUPPORT_LOCK_H
21
22 #include <pthread.h>
23 #include <cstdlib>
24
25 namespace llvm {
26
27 /// Lock - Abstract class that provides mutual exclusion (also known
28 /// as a mutex.)
29 ///
30 class Lock {
31 protected:
32   virtual ~Lock() {}                        // Derive from me
33 public:
34   virtual void acquire () { abort (); }
35   virtual void release () { abort (); }
36
37   /// create - Static method that returns a Lock of the correct class
38   /// for the current host OS.
39   ///
40   static Lock create ();
41 };
42
43 /// POSIXLock - Specialization of Lock class implemented using
44 /// pthread_mutex_t objects.
45 ///
46 class POSIXLock : public Lock {
47   pthread_mutex_t mutex;
48 public:
49   POSIXLock () { pthread_mutex_init (&mutex, 0); }
50   virtual ~POSIXLock () { pthread_mutex_destroy (&mutex); }
51   virtual void acquire () { pthread_mutex_lock (&mutex); }
52   virtual void release () { pthread_mutex_unlock (&mutex); }
53 };
54
55 /// LockHolder - Instances of this class acquire a given Lock when
56 /// constructed and hold that lock until destruction.  Uncle Bjarne
57 /// says, "Resource acquisition is allocation." Or is it the other way
58 /// around? I never can remember.
59 ///
60 class LockHolder {
61   Lock &L;
62 public:
63   LockHolder (Lock &_L) : L (_L) { L.acquire (); }
64   ~LockHolder () { L.release (); }
65 };
66
67 } // end namespace llvm
68
69 #endif // SUPPORT_LOCK_H