Advertisement
Guest User

Martin

a guest
Mar 19th, 2013
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
D 1.64 KB | None | 0 0
  1. module refcounting;
  2.  
  3. import core.exception;
  4. import std.c.stdlib;
  5.  
  6. __gshared Object lock;
  7. __gshared int[void*] refCounts;
  8.  
  9. shared static this()
  10. {
  11.  
  12.     enum objSize = __traits(classInstanceSize, Object);
  13.    
  14.     void* memory = malloc(objSize);
  15.  
  16.     if (!memory)
  17.     {
  18.         throw new OutOfMemoryError;
  19.     }
  20.  
  21.     lock = emplace!(Object)(memory[0..objSize]);
  22.    
  23. }
  24.  
  25. struct RefCountedObj(T)
  26.     if (is(T == class))
  27. {
  28. private:
  29.     T _val;
  30.    
  31. public:
  32.     alias _val this;
  33.    
  34.     static RefCountedObj!(T) create(Args...)(Args args)
  35.     {
  36.        
  37.         RefCountedObj!(T) obj;
  38.         obj._val = alloc!(T)(args);
  39.        
  40.         return obj;
  41.        
  42.     }
  43.    
  44.     this(this)
  45.     {
  46.        
  47.         synchronized(lock)
  48.         {
  49.             ++refCounts[cast(void*)_val];
  50.         }
  51.        
  52.     }
  53.    
  54.     ~this()
  55.     {
  56.        
  57.         synchronized(lock)
  58.         {
  59.            
  60.             int refCount = --refCounts[cast(void*)_val];
  61.            
  62.             if (refCount == 0)
  63.             {
  64.                 _val.__dtor;
  65.                 free(cast(void*)_val);
  66.             }
  67.         }
  68.        
  69.     }
  70.    
  71.     void opAssign(T value)
  72.     {
  73.        
  74.         if (cast(void*)value != cast(void*)_val)
  75.         {
  76.            
  77.             synchronized(lock)
  78.             {
  79.                
  80.                 int refCount = --refCounts[cast(void*)_val];
  81.                
  82.                 if (refCount == 0)
  83.                 {
  84.                     _val.__dtor;
  85.                     free(cast(void*)_val);
  86.                 }
  87.                
  88.             }
  89.            
  90.         }
  91.        
  92.     }
  93.    
  94. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement