1 //===-- Support/Lock.h - Platform-agnostic mutual exclusion -----*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
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
17 //===----------------------------------------------------------------------===//
19 #ifndef SUPPORT_LOCK_H
20 #define SUPPORT_LOCK_H
27 /// Lock - Abstract class that provides mutual exclusion (also known
32 virtual ~Lock() {} // Derive from me
34 virtual void acquire () { abort (); }
35 virtual void release () { abort (); }
37 /// create - Static method that returns a Lock of the correct class
38 /// for the current host OS.
40 static Lock create ();
43 /// POSIXLock - Specialization of Lock class implemented using
44 /// pthread_mutex_t objects.
46 class POSIXLock : public Lock {
47 pthread_mutex_t mutex;
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); }
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.
63 LockHolder (Lock &_L) : L (_L) { L.acquire (); }
64 ~LockHolder () { L.release (); }
67 } // end namespace llvm
69 #endif // SUPPORT_LOCK_H