Advertisement
Guest User

Untitled

a guest
Nov 21st, 2014
233
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.63 KB | None | 0 0
  1. class FreeQueue
  2. {
  3.   const static int BUFFERS = 2;
  4.   const static int SIZE = 128;
  5.   FixedVector<void*,SIZE> ptrs[BUFFERS];
  6.   int currentQueue;
  7.   Atomic ownedByJob[BUFFERS];
  8. public:
  9.   FreeQueue() : currentQueue() {}
  10.  
  11.   void Push(void* ptr)
  12.   {
  13.     while(1)
  14.     {
  15.       if( currentQueue==-1 ) // worst case, all buffers are full and jobs haven't completed yet
  16.       {
  17.         ThreadPool::WaitUntil( IsFalse(ownedByJob, BUFFERS) ); // go idle and/or run available jobs
  18.         for( int i=0; i!=BUFFERS && currentQueue==-1; ++i )
  19.           if( ownedByJob[i] == 0 )
  20.             currentQueue = i;
  21.       }
  22.       assert( currentQueue!=-1 );
  23.       if( ptrs[currentQueue]->Push(ptr) )
  24.         return;//actualy pushed the ptr into a buffer
  25.       else//failed to push, this buffer is full
  26.       {
  27.         //mark this buffer as being owned by a job, kick of the async call to actually free the pointers in that buffer
  28.         ownedByJob[currentQueue] = 1;
  29.         ThreadPool::PushJob( ActuallyCallFree(ptrs[currentQueue], ownedByJob[currentQueue]) );
  30.         // ActuallyCallFree does: foreach ptr in arg0: _real_free_(ptr); arg0.clear(); arg1 = 0;
  31.  
  32.         currentQueue = (currentQueue+1) % BUFFERS;//try to move to the next buffer
  33.         if( ownedByJob[currentQueue] )// next buffer is still waiting for it's job to complete, try find another one
  34.         {
  35.           currentQueue = -1;
  36.           for( int i=0; i!=BUFFERS && currentQueue==-1; ++i )
  37.             if( ownedByJob[i] == 0 )
  38.               currentQueue = i;
  39.         }
  40.       }
  41.     }
  42.   }
  43. };
  44.  
  45. static ThreadLocal<FreeQueue> g_toFree;
  46.  
  47. void free(void* p)
  48. {
  49.   g_toFree->push(p);
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement