void SlotVisitor::copyLater(JSCell* owner, CopyToken token, void* ptr, size_t bytes)
{
    ASSERT(bytes);
    CopiedBlock* block = CopiedSpace::blockFor(ptr);
    if (block->isOversize()) {
        ASSERT(bytes <= block->size());
        // FIXME: We should be able to shrink the allocation if bytes went below the block size.
        // For now, we just make sure that our accounting of how much memory we are actually using
        // is correct.
        // https://bugs.webkit.org/show_bug.cgi?id=144749
        bytes = block->size();
        m_heap.m_storageSpace.pin(block);
    }

    ASSERT(heap()->m_storageSpace.contains(block));

    LockHolder locker(&block->workListLock());
    // We always report live bytes, except if during an eden collection we see an old object pointing to an
    // old backing store and the old object is being marked because of the remembered set. Note that if we
    // ask the object itself, it will always tell us that it's an old black object - because even during an
    // eden collection we have already indicated that the object is old. That's why we use the
    // SlotVisitor's cache of the object's old state.
    if (heap()->operationInProgress() == FullCollection
        || !block->isOld()
        || m_currentObjectCellStateBeforeVisiting != CellState::OldGrey) {
        m_bytesCopied += bytes;
        block->reportLiveBytes(locker, owner, token, bytes);
    }
}
Beispiel #2
0
static void C_section_comment(FILE *f)
{
    PAD;
    int c = getc(f);
    char *p;
    section *s;
    while (c == '\r') c = getc(f);
    if (c == '!')
    {   C_product_comment(f);
        return;
    }
    read_header(f, c, "section");
/* Here I have the case
 *    /*!! section [alphakey] title
 */
    p = header;
    while (*p == ' ') p++;
    if (*p == 0)
    {   printf("Empty section directive\n");
        exit(1);
    }
    n_secname = n_alphakey = n_sechdr = 0;
    secname[0] = 0;
    alphakey[0] = 0;
    sechdr[0] = 0;
    for (;;)
    {   c = *p++;
        if (n_secname < MAX_SECNAME) secname[n_secname++] = c;
        if (*p == 0 || *p == ' ') break;
    }
    while (*p == ' ') p++;
    if (*p == '[')
    {   p++;
        while ((c = *p++) != 0 && c != ']')
        {   if (n_alphakey < MAX_ALPHAKEY) alphakey[n_alphakey++] = c;
        }
        if (c == ']') p++;
    }
    while (*p == ' ') p++;
    if (*p != 0)
    {   for (;;)
        {   c = *p++;
            if (n_sechdr < MAX_SECHDR) sechdr[n_sechdr++] = c;
            if (*p == 0) break;
        }
    }
    secname[n_secname] = 0;
    alphakey[n_alphakey] = 0;
    sechdr[n_sechdr] = 0;
/* If no alphakey is explicitly given then use the section heading */
    if (n_alphakey == 0) strcpy(alphakey, sechdr);
//  printf("Section: %s\n", secname);
//  printf("AlphaKey: %s\n", alphakey);
//  printf("Heading: %s\n", sechdr);
    p = C_until_comment_end(f, active);
    s = find_section(secname);
    s->alphakey = heap(alphakey);
    s->sechdr = heap(sechdr);
    s->text = heap(p);
}
Beispiel #3
0
MarkedBlock::FreeList MarkedBlock::sweepHelper(SweepMode sweepMode)
{
    switch (m_state) {
    case New:
        ASSERT(sweepMode == SweepToFreeList);
        return specializedSweep<New, SweepToFreeList, destructorCallNeeded>();
    case FreeListed:
        // Happens when a block transitions to fully allocated.
        ASSERT(sweepMode == SweepToFreeList);
        return FreeList();
    case Allocated:
        ASSERT_NOT_REACHED();
        return FreeList();
    case Marked:
        ASSERT(!m_onlyContainsStructures || heap()->isSafeToSweepStructures());
        return sweepMode == SweepToFreeList
            ? specializedSweep<Marked, SweepToFreeList, destructorCallNeeded>()
            : specializedSweep<Marked, SweepOnly, destructorCallNeeded>();
    case Zapped:
        ASSERT(!m_onlyContainsStructures || heap()->isSafeToSweepStructures());
        return sweepMode == SweepToFreeList
            ? specializedSweep<Zapped, SweepToFreeList, destructorCallNeeded>()
            : specializedSweep<Zapped, SweepOnly, destructorCallNeeded>();
    }

    ASSERT_NOT_REACHED();
    return FreeList();
}
Beispiel #4
0
WeakBlock::FreeCell* WeakSet::addAllocator()
{
    WeakBlock* block = WeakBlock::create(heap()->blockAllocator().allocate<WeakBlock>());
    heap()->didAllocate(WeakBlock::blockSize);
    m_blocks.append(block);
    WeakBlock::SweepResult sweepResult = block->takeSweepResult();
    ASSERT(!sweepResult.isNull() && sweepResult.freeList);
    return sweepResult.freeList;
}
Beispiel #5
0
static void lisp_doc_comment(FILE *f)
{
    PAD;
    int c;
    char *p;
    section *s;
/* Here I have the case
 *    %%! section subsection-title
 * or %%! section [alphakey] subsection-title
 */
    p = line+3;
    while (*p == ' ') p++;
    if (*p == 0)
    {   printf("Empty subsection directive\n");
        exit(1);
    }
    n_secname = n_alphakey = n_subsechdr = 0;
    secname[0] = 0;
    alphakey[0] = 0;
    subsechdr[0] = 0;
    for (;;)
    {   c = *p++;
        if (n_secname < MAX_SECNAME) secname[n_secname++] = c;
        if (*p == 0 || *p == ' ') break;
    }
    while (*p == ' ') p++;
    if (*p == '[')
    {   p++;
        while ((c = *p++) != 0 && c != ']')
        {   if (n_alphakey < MAX_ALPHAKEY) alphakey[n_alphakey++] = c;
        }
        if (c == ']') p++;
    }
    while (*p == ' ') p++;
    if (*p != 0)
    {   for (;;)
        {   c = *p++;
            if (n_subsechdr < MAX_SUBSECHDR) subsechdr[n_subsechdr++] = c;
            if (*p == 0) break;
        }
    }
    secname[n_secname] = 0;
    alphakey[n_alphakey] = 0;
    subsechdr[n_subsechdr] = 0;
/* If no alphakey is explicitly given then use the subsection heading */
    if (n_alphakey == 0) strcpy(alphakey, subsechdr);
//  printf("Section: %s\n", secname);
//  printf("AlphaKey: %s\n", alphakey);
//  printf("Sub Heading: %s\n", subsechdr);
    p = lisp_until_comment_end(f, active);
    s = find_section(secname);
    s->parts = make_subsection(heap(alphakey), heap(subsechdr),
                               heap(p), s->parts);
}
Beispiel #6
0
void SlotVisitor::didStartMarking()
{
    if (heap()->collectionScope() == CollectionScope::Full)
        ASSERT(m_opaqueRoots.isEmpty()); // Should have merged by now.
    else
        reset();

    if (HeapProfiler* heapProfiler = vm().heapProfiler())
        m_heapSnapshotBuilder = heapProfiler->activeSnapshotBuilder();
    
    m_markingVersion = heap()->objectSpace().markingVersion();
}
Beispiel #7
0
WeakBlock::FreeCell* WeakSet::addAllocator()
{
    if (!isOnList())
        heap()->objectSpace().addActiveWeakSet(this);
    
    WeakBlock* block = WeakBlock::create(*heap(), m_container);
    heap()->didAllocate(WeakBlock::blockSize);
    m_blocks.append(block);
    WeakBlock::SweepResult sweepResult = block->takeSweepResult();
    ASSERT(!sweepResult.isNull() && sweepResult.freeList);
    return sweepResult.freeList;
}
main() {

	Heap heap(15);	// sets array size to 20

	srand((unsigned)time(NULL));	// seeds random # generator
									// to ensure different #
									// each call to rand()

	for (int i = 0; i < 15; i++) {		// puts random #'s into array
		heap.Insert_temp_Array(((double) (rand() * 20) / RAND_MAX));
	}
	heap.temp_Print();					// print array

	for (int x = 1; x < 16; x++) {		// insert #'s from array into heap
		heap.Insert(heap.Get_temp_Array[x-1]);
	}

	heap.Print();						// print heap

	heap.Reset_temp_Array();			// reset array to size of 0
	for (int y = 0; y < 15; y++) {		// sort #'s from heap into array
		heap.Insert_temp_Array(heap.DeleteMin());
	}
		
	heap.temp_Print();					// print sorted array

	return 0;

}
Beispiel #9
0
rc_t fullPipelineTest(ss_m* ssm, test_volume_t* test_vol)
{
    unsigned howManyToInsert = 1000;
    W_DO(populateBtree(ssm, test_vol, howManyToInsert));

    LogArchiver::LogConsumer cons(lsn_t(1,0), BLOCK_SIZE);
    LogArchiver::ArchiverHeap heap(BLOCK_SIZE);
    LogArchiver::ArchiveDirectory dir(test_env->archive_dir, BLOCK_SIZE);
    LogArchiver::BlockAssembly assemb(&dir);

    LogArchiver la(&dir, &cons, &heap, &assemb);
    la.fork();
    la.activate(lsn_t::null, true /* wait */);

    // nextLSN of consumer tells us that all logrecs up (and excluding) that
    // LSN were added to the heap. When shutdown is invoked, heap is then emptied
    // using the selection method, thus also gauaranteeing that the archive is persistent
    // up to nextLSN
    while (cons.getNextLSN() < ssm->log->durable_lsn()) {
        usleep(1000); // 1ms
    }

    la.shutdown();
    la.join();

    // TODO use archive scanner to verify:
    // 1) integrity of archive
    // 2) if no logrecs are missing (scan log with same ignores as log archiver
    // and check if each logrec is in archiver -- random access, NL join)

    return RCOK;
}
Beispiel #10
0
// TODO implement heapTestFactory that uses LogFactory
rc_t heapTestReal(ss_m* ssm, test_volume_t* test_vol)
{
    unsigned howManyToInsert = 1000;
    W_DO(populateBtree(ssm, test_vol, howManyToInsert));

    lsn_t lastLSN = ssm->log->durable_lsn();
    lsn_t prevLSN = lsn_t(1,0);
    LogArchiver::LogConsumer cons(prevLSN, BLOCK_SIZE);
    cons.open(lastLSN);

    LogArchiver::ArchiverHeap heap(BLOCK_SIZE);

    logrec_t* lr;
    bool pushed = false;
    while (cons.next(lr)) {
        pushed = heap.push(lr, false);
        if (!pushed) {
            emptyHeapAndCheck(heap);
            pushed = heap.push(lr, false);
            EXPECT_TRUE(pushed);
        }
    }

    emptyHeapAndCheck(heap);
    EXPECT_EQ(0, heap.size());

    return RCOK;
}
Beispiel #11
0
void euclid_lsh::neighbor_row_from_hash(
    const bit_vector& bv,
    float norm,
    vector<pair<string, float> >& ids,
    uint64_t ret_num) const {
  // This function is not thread safe.
  // Take lock out of this function.
  jubatus::util::lang::shared_ptr<const column_table> table =
    get_const_table();
  const_bit_vector_column& bv_col = lsh_column();
  const_float_column& norm_col = norm_column();
  const float denom = bv.bit_num();
  heap_t heap(ret_num);
  jubatus::util::lang::function<heap_t(size_t, size_t)> f =
    jubatus::util::lang::bind(
      &ranking_hamming_bit_vectors_worker, &bv, &bv_col, &norm_col,
      denom, norm, ret_num,
      jubatus::util::lang::_1, jubatus::util::lang::_2);
  ranking_hamming_bit_vectors_internal(
      f, table->size_nolock(), threads_, heap);

  vector<pair<float, size_t> > sorted;
  heap.get_sorted(sorted);

  ids.clear();
  for (size_t i = 0; i < sorted.size(); ++i) {
    ids.push_back(make_pair(
      table->get_key_nolock(sorted[i].second), sorted[i].first));
  }
}
Beispiel #12
0
CheckedBoolean CopiedSpace::tryReallocateOversize(void** ptr, size_t oldSize, size_t newSize)
{
    ASSERT(isOversize(oldSize) || isOversize(newSize));
    ASSERT(newSize > oldSize);

    void* oldPtr = *ptr;
    
    void* newPtr = 0;
    if (!tryAllocateOversize(newSize, &newPtr)) {
        *ptr = 0;
        return false;
    }

    memcpy(newPtr, oldPtr, oldSize);

    CopiedBlock* oldBlock = CopiedSpace::blockFor(oldPtr);
    if (oldBlock->isOversize()) {
        // FIXME: Eagerly deallocating the old space block probably buys more confusion than
        // value.
        // https://bugs.webkit.org/show_bug.cgi?id=144750
        if (oldBlock->isOld()) {
            m_bytesRemovedFromOldSpaceDueToReallocation += oldBlock->size();
            m_oldGen.oversizeBlocks.remove(oldBlock);
        } else
            m_newGen.oversizeBlocks.remove(oldBlock);
        m_blockSet.remove(oldBlock);
        CopiedBlock::destroy(*heap(), oldBlock);
    }
    
    *ptr = newPtr;
    return true;
}
Beispiel #13
0
int main(int argc, char **argv)
{
	int arr[50],i,n;
	printf("Enter the no elements : ");
	scanf("%d",&n);
	printf("Enter The Elements : ");
	for(i=0;i<n;i++){
		scanf("%d",&arr[i]);
		}

	printf("\nArray : ");
	for(i=0;i<n;i++){
		printf("%d ",arr[i]);
		}
	
	
	printf("\n HEAP : ");
	heap(arr,n);
	for(i=0;i<n;i++){
	    printf("%d ",arr[i]);
	    }
	 
   printf("\n heapsort : ");
   heapsort(arr,n);
   for(i=0;i<n;i++){
      printf("%d ",arr[i]);
	    }
	 getch();
	return 0;
}
void heap(int tes)
{
    int i,j,k,l,r;
    l=2*tes;
    r=2*tes+1;
    if(l<=n)
    {
        if(r<=n)
        {
            if(inp[l][1]>inp[r][1])
                i=l;
            else
                i=r;
        }
        else
            i=l;
        if(inp[tes][1]<inp[i][1])
        {
            j=inp[tes][0];
            k=inp[tes][1];
            inp[tes][1]=inp[i][1];
            inp[tes][0]=inp[i][0];
            inp[i][0]=j;
            inp[i][1]=k;
            heap(i);
        }
    }
}
CmpStatement::ReturnStatus
CmpStatement::process (const CmpMessageUpdateHist& statement)
{
  // A pointer to user SQL query is stored in CmpStatement; if an exception is
  // thrown the user query is copied from here. It is reset upon return from
  // the UpdateStats() method.
  
  char *userStr= new (heap()) char[2000];
#pragma nowarn(1506)   // warning elimination 
  Int32 len=strlen(statement.data());
#pragma warn(1506)  // warning elimination 

  if (len > 1999)
    len=1999;

  strncpy(userStr, statement.data(), len);
  userStr[len]='\0'; 

  sqlTextStr_ = userStr;

  if (UpdateStats(statement.data()))
     {
       sqlTextStr_=NULL;
       return CmpStatement_ERROR;
     }

  sqlTextStr_=NULL;
  return CmpStatement_SUCCESS;
}
/*Programa Pricipal */
int main(void)
{
	register int n, i;
	printf("Quantos elementos devem ser ordenados: ");
	scanf("%d", &n);
	register int vet[n];
	for(i = 0; i < n; i++){
		printf("Digite o valor do elemento %d: ", i+1);
		fflush(stdin); //Caso o usuário entre com char, o programa correrá "normalmente"
		scanf("%d", &vet[i]);
	}
	// Ordenar o vetor por heap sort
	heap(vet, n);
	// Exibir vetor ordenado
	printf("Seu vetor ordenado:\n");
	for(i = 0; i < n; i++){
        printf("| %d ", vet[i]);
        if(i == n-1){
            printf("|");
        }
	}
	printf("\nDigite o valor a ser pesquisado: ");
	scanf("%d", &i);
	bin_busca(vet, i, 0, n);
	getchar();
	getchar();
}
Beispiel #17
0
void euclid_lsh::neighbor_row_from_hash(
    const bit_vector& bv,
    float norm,
    vector<pair<string, float> >& ids,
    uint64_t ret_num) const {
  jubatus::util::lang::shared_ptr<const column_table> table = get_const_table();

  jubatus::core::storage::fixed_size_heap<pair<float, size_t> > heap(ret_num);
  {
    const_bit_vector_column& bv_col = lsh_column();
    const_float_column& norm_col = norm_column();

    const float denom = bv.bit_num();
    for (size_t i = 0; i < table->size(); ++i) {
      const size_t hamm_dist = bv.calc_hamming_distance(bv_col[i]);
      const float theta = hamm_dist * M_PI / denom;
      const float score = norm_col[i] * (norm_col[i] - 2 * norm * cos(theta));
      heap.push(make_pair(score, i));
    }
  }

  vector<pair<float, size_t> > sorted;
  heap.get_sorted(sorted);

  ids.clear();
  const float squared_norm = norm * norm;
  for (size_t i = 0; i < sorted.size(); ++i) {
    ids.push_back(make_pair(table->get_key(sorted[i].second),
                            sqrt(squared_norm + sorted[i].first)));
  }
}
Beispiel #18
0
TEST(HeapTest, CopyTest)
{
    const int SIZE = 20;    
    int* array = new int[SIZE];
    for (int i = 0; i < SIZE; i++)
    {
        array[i] = i;
    }

    Heap<int> heap(array, SIZE);
    EXPECT_EQ(heap.getNumNodes(), SIZE);

    delete[] array;

    array = new int[SIZE];
    for (int i = 0; i < SIZE; i++)
    {
        array[i] = heap.peekTop();
        heap.remove();
    }

    for (int i = SIZE - 1; i >= 0; i--)
    {
        EXPECT_EQ(i, array[SIZE - i - 1]);
    }

    delete[] array;
}
Beispiel #19
0
void SlotVisitor::didStartMarking()
{
    if (heap()->operationInProgress() == FullCollection)
        ASSERT(m_opaqueRoots.isEmpty()); // Should have merged by now.

    m_shouldHashCons = m_heap.m_shouldHashCons;
}
Beispiel #20
0
BOOST_FIXTURE_TEST_CASE_TEMPLATE(decrease_key_test, T, storage_types, RandomDataFixture<10>)
{
    BinaryHeap<TestNodeID, TestKey, TestWeight, TestData, T> heap(10);

    for (unsigned idx : order)
    {
        heap.Insert(ids[idx], weights[idx], data[idx]);
    }

    std::vector<TestNodeID> rids(ids);
    std::reverse(rids.begin(), rids.end());

    for (auto id : rids)
    {
        TestNodeID min_id = heap.Min();
        TestWeight min_weight = heap.GetKey(min_id);

        // decrease weight until we reach min weight
        while (weights[id] > min_weight)
        {
            heap.DecreaseKey(id, weights[id]);
            BOOST_CHECK_EQUAL(heap.Min(), min_id);
            BOOST_CHECK_EQUAL(heap.MinKey(), min_weight);
            weights[id]--;
        }

        // make weight smaller than min
        weights[id] -= 2;
        heap.DecreaseKey(id, weights[id]);
        BOOST_CHECK_EQUAL(heap.Min(), id);
        BOOST_CHECK_EQUAL(heap.MinKey(), weights[id]);
    }
}
Beispiel #21
0
BOOST_FIXTURE_TEST_CASE_TEMPLATE(insert_test, T, storage_types, RandomDataFixture<NUM_NODES>)
{
    BinaryHeap<TestNodeID, TestKey, TestWeight, TestData, T> heap(NUM_NODES);

    TestWeight min_weight = std::numeric_limits<TestWeight>::max();
    TestNodeID min_id;

    for (unsigned idx : order)
    {
        BOOST_CHECK(!heap.WasInserted(ids[idx]));

        heap.Insert(ids[idx], weights[idx], data[idx]);

        BOOST_CHECK(heap.WasInserted(ids[idx]));

        if (weights[idx] < min_weight)
        {
            min_weight = weights[idx];
            min_id = ids[idx];
        }
        BOOST_CHECK_EQUAL(min_id, heap.Min());
    }

    for (auto id : ids)
    {
        const auto &d = heap.GetData(id);
        BOOST_CHECK_EQUAL(d.value, data[id].value);

        const auto &w = heap.GetKey(id);
        BOOST_CHECK_EQUAL(w, weights[id]);
    }
}
Beispiel #22
0
// Dijkstra's algorithim for computing shortest path
void Graph::computeShortestPaths(int aNodeId)
{
  initializeShortestPath(aNodeId);

  Heap<Node*> heap(numNodes());

  // Insert all the nodes into the heap
  for (const SLLNode<Node*>* curr = mNodes.head();
       curr != NULL; curr = curr->next()) {
    Node* currNode = curr->value();
    heap.insertIgnoringHeapOrder(currNode);
  }

  // Heapify into a min heap
  heap.bottomUpMinHeap();

  // You can call heap.removeMin() to extract the min
  while(!heap.isEmpty()){
    Node* u = heap.removeMin();
    SLinkedList<Edge*> edges = u->getEdges();
    for (SLLNode<Edge*>* curr = edges.head();
       curr != NULL; curr = curr->next()){
        Edge* e = curr->value();
        relax(e);
    }
    heap.bottomUpMinHeap();
  }

}
void bit_index_storage::similar_row(
    const bit_vector& bv,
    vector<pair<string, float> >& ids,
    uint64_t ret_num) const {
  ids.clear();
  uint64_t bit_num = bv.bit_num();
  if (bit_num == 0) {
    return;
  }

  heap_type heap(ret_num);

  for (bit_table_t::const_iterator it = bitvals_diff_.begin();
      it != bitvals_diff_.end(); ++it) {
    similar_row_one(bv, *it, heap);
  }
  for (bit_table_t::const_iterator it = bitvals_.begin(); it != bitvals_.end();
      ++it) {
    if (bitvals_diff_.find(it->first) != bitvals_diff_.end()) {
      continue;
    }
    similar_row_one(bv, *it, heap);
  }

  vector<pair<uint64_t, string> > scores;
  heap.get_sorted(scores);
  for (size_t i = 0; i < scores.size() && i < ret_num; ++i) {
    ids.push_back(make_pair(scores[i].second,
                            static_cast<float>(scores[i].first) / bit_num));
  }
}
Beispiel #24
0
void conditionalSend(bool forceSend) {

  int rtcIt = rtcMemStore.getIterations();
  //Serial << "rtcit = " << rtcIt << endl;
  //Serial.flush();
  if (rtcIt == 0) forceSend = true;
  rtcIt ++;
  if (rtcIt >= PropertyList.readLongProperty(PROP_SND_INT) / PowerManagerClass::IterationDurationS) rtcIt = 0;
  rtcMemStore.setIterations(rtcIt);
  Serial << F("\n--- DestHanlder: sendValue --- ") << forceSend<< endl;
  Serial.flush();
  LinkedList<Pair *> values = LinkedList<Pair* >();
  addCommonValues(&values);
  for (int i=0; i < sensors.size(); i++)  sensors.get(i)->getData(&values);

  //bool someThresholdExceeded = checkThresholds(values);
//  if (forceSend || someThresholdExceeded) {
//  wifiConnectMulti();

  if (forceSend) {
    for (int i=0; i < destinations.size(); i++) destinations.get(i)->process(values);
  //tmrSendValueTimer->Start();
  }
//  wifiOff();

  for (int i=0; i < values.size(); i++)  delete  values.get(i);
  if (DEBUG) heap("");
  tmrRawRead->setInterval(PowerManagerClass::IterationDurationS * 1000);
  tmrRawRead->Start();

}
main() {

	Heap heap(15);	// sets array size to 20

	srand((unsigned)time(NULL));	// seeds random # generator
									// to ensure different #
									// each call to rand()

	for (int i = 0; i < 15; i++) {		// puts random #'s into array
		heap.temp_Array[i] = (double) (rand() * 20) / RAND_MAX;
		cout<<"Array element "<<i<<" is "<<heap.temp_Array[i]<<'\n';
	}

	for (int x = 1; x < 16; x++) {		// insert #'s from array into heap
		heap.Insert(heap.temp_Array[x-1]);
	}

	heap.Print();						// print heap

	for (int y = 0; y < 15; y++) {		// sort #'s from heap into array
		heap.temp_Array[y] = heap.DeleteMin();
	}
		
	cout<<"Sorted array is: "<<'\n';	// print sorted array
	for (int z=0; z<15; z++) cout<<heap.temp_Array[z]<<"  ";
	cout<<'\n';

	return 0;

}
void CopiedSpace::doneCopying()
{
    {
        MutexLocker locker(m_loanedBlocksLock);
        while (m_numberOfLoanedBlocks > 0)
            m_loanedBlocksCondition.wait(m_loanedBlocksLock);
    }

    ASSERT(m_inCopyingPhase == m_shouldDoCopyPhase);
    m_inCopyingPhase = false;

    DoublyLinkedList<CopiedBlock>* toSpace;
    DoublyLinkedList<CopiedBlock>* fromSpace;
    TinyBloomFilter* blockFilter;
    if (heap()->operationInProgress() == FullCollection) {
        toSpace = m_oldGen.toSpace;
        fromSpace = m_oldGen.fromSpace;
        blockFilter = &m_oldGen.blockFilter;
    } else {
        toSpace = m_newGen.toSpace;
        fromSpace = m_newGen.fromSpace;
        blockFilter = &m_newGen.blockFilter;
    }

    while (!fromSpace->isEmpty()) {
        CopiedBlock* block = fromSpace->removeHead();
        // We don't add the block to the blockSet because it was never removed.
        ASSERT(m_blockSet.contains(block));
        blockFilter->add(reinterpret_cast<Bits>(block));
        toSpace->push(block);
    }

    if (heap()->operationInProgress() == EdenCollection) {
        m_oldGen.toSpace->append(*m_newGen.toSpace);
        m_oldGen.oversizeBlocks.append(m_newGen.oversizeBlocks);
        m_oldGen.blockFilter.add(m_newGen.blockFilter);
        m_newGen.blockFilter.reset();
    }

    ASSERT(m_newGen.toSpace->isEmpty());
    ASSERT(m_newGen.fromSpace->isEmpty());
    ASSERT(m_newGen.oversizeBlocks.isEmpty());

    allocateBlock();

    m_shouldDoCopyPhase = false;
}
Beispiel #27
0
inline Handler<ObjectT> HeapProvider::newInstance(ProviderT* self, Args... args)
{
    Handler<Heap> heap(self->heap().lock());
    if( unlikely(!heap) ) {
        DONUT_EXCEPTION(Exception, "[BUG] Heap is already dead.");
    }
    return heap->createObject<ObjectT>(self, args...);
}
Beispiel #28
0
sp<IMemory> MemoryDealer::allocate(size_t size)
{
    sp<IMemory> memory;
    const ssize_t offset = allocator()->allocate(size);
    if (offset >= 0) {
        memory = new Allocation(this, heap(), offset, size);
    }
    return memory;
}
////////////////////////////////////////////////////////////////
//    DIJKSTRA(START, GOAL) and TERMINATE WHEN GOAL IS KNOWN  //
////////////////////////////////////////////////////////////////
void Router::Dijkstra(Vertex* start, Vertex* goal){
      //Initialized Minheap
      BinaryHeap heap(nFlights);
      Edge* pt=start->first;
      unsigned int newCost;
      while(pt!=0)
      {
          newCost=calCostOrigin(start,pt);
          //we update the cost if it is smaller
         if(newCost< vArray[pt->index]->dist)
        {
          vArray[pt->index]->dist=newCost;
          vArray[pt->index]->pv = pt->edgeNum; //denote previous vertice using previous edge/flight num
          vArray[pt->index]->previous=start->index; //set previous vertice
          //Dump the (vertice, dist) pairs into the heap;
    
          HeapObj* temp= new HeapObj(pt->index, newCost); //push each updated vertex dist pair into the heap
          heap.insert(temp);
        }
          
          pt=pt->next; //move to the next
      }
       
  
  do{
       //FIND MINIMUM DISTANCE IN UNKNOWN VERTICES MARK AS KNOW
       HeapObj* minUnknown=FindMinUnknown(heap);
       vArray[minUnknown->index]->known=true;
       
       
       //
       
       //clocktime at new pivot is equal to trip departuretime + the dist(duration of travel)
       vArray[minUnknown->index]->clock=start->clock+vArray[minUnknown->index]->dist;

       
       pt=vArray[minUnknown->index]->first;
       while(pt!=0)
       {
            if(!vArray[pt->index]->known)  //do the following only to unknown vertex
           {
            newCost=calCost(vArray[minUnknown->index],pt);
            //if this Total_cost is less than the cost update
            if(newCost< vArray[pt->index]->dist)
            {
               vArray[pt->index]->dist=newCost;
               vArray[pt->index]->pv = pt->edgeNum; //denote previous vertice using previous edge/flight num
               vArray[pt->index]->previous=minUnknown->index; //Set previous vertice index
               HeapObj* temp= new HeapObj(pt->index, newCost); //push each updated vertex dist pair into the heap
               heap.insert(temp);
            }
           }
            pt=pt->next;
            
       }
    }while(!goal->known);
}
Beispiel #30
0
void
mono_gc_collect (int generation)
{
    // TODO
    if (!gc_initialized)
      return;

    heap()->GarbageCollect(generation);
}