source: proiecte/swift/trunk/lib/hoard-371/src/heapmanager.h @ 176

Last change on this file since 176 was 176, checked in by (none), 14 years ago
  • imported repo from "guagal"
File size: 2.1 KB
Line 
1// -*- C++ -*-
2
3#ifndef _HEAPMANAGER_H_
4#define _HEAPMANAGER_H_
5
6#include <stdlib.h>
7
8#include "guard.h"
9#include "cpuinfo.h"
10
11namespace Hoard {
12
13  template <typename LockType,
14            typename HeapType>
15  class HeapManager : public HeapType {
16  public:
17
18    HeapManager (void)
19    {
20      HL::Guard<LockType> g (heapLock);
21     
22      /// Initialize all heap maps (nothing yet assigned).
23      int i;
24      for (i = 0; i < HeapType::MaxThreads; i++) {
25        HeapType::setTidMap (i, 0);
26      }
27      for (i = 0; i < HeapType::MaxHeaps; i++) {
28        HeapType::setInusemap (i, 0);
29      }
30    }
31
32    /// Set this thread's heap id to 0.
33    void chooseZero (void) {
34      HL::Guard<LockType> g (heapLock);
35      HeapType::setTidMap ((int) HL::CPUInfo::getThreadId() % MaxThreads, 0);
36    }
37
38    int findUnusedHeap (void) {
39
40      HL::Guard<LockType> g (heapLock);
41     
42      unsigned int tid_original = HL::CPUInfo::getThreadId();
43      unsigned int tid = tid_original % HeapType::MaxThreads;
44     
45      int i = 0;
46      while ((i < HeapType::MaxHeaps) && (HeapType::getInusemap(i)))
47        i++;
48      if (i >= HeapType::MaxHeaps) {
49        // Every heap is in use: pick heap one.
50        i = 0;
51      }
52     
53      HeapType::setInusemap (i, 1);
54      HeapType::setTidMap (tid, i);
55     
56      return i;
57    }
58
59    void releaseHeap (void) {
60      // Decrement the ref-count on the current heap.
61     
62      HL::Guard<LockType> g (heapLock);
63     
64      // Statically ensure that the number of threads is a power of two.
65      enum { VerifyPowerOfTwo = 1 / ((HeapType::MaxThreads & ~(HeapType::MaxThreads-1))) };
66     
67      int tid = HL::CPUInfo::getThreadId() & (HeapType::MaxThreads - 1);
68      int heapIndex = HeapType::getTidMap (tid);
69     
70      HeapType::setInusemap (heapIndex, 0);
71     
72      // Prevent underruns (defensive programming).
73     
74      if (HeapType::getInusemap (heapIndex) < 0) {
75        HeapType::setInusemap (heapIndex, 0);
76      }
77    }
78   
79   
80  private:
81   
82    // Disable copying.
83   
84    HeapManager (const HeapManager&);
85    HeapManager& operator= (const HeapManager&);
86   
87    /// The lock, to ensure mutual exclusion.
88    LockType heapLock;
89  };
90
91};
92
93#endif
Note: See TracBrowser for help on using the repository browser.