diff --git a/contrib/parallel_dummy/parallel_dummy.c b/contrib/parallel_dummy/parallel_dummy.c index 0a32ea8..0b75694 100644 --- a/contrib/parallel_dummy/parallel_dummy.c +++ b/contrib/parallel_dummy/parallel_dummy.c @@ -43,8 +43,13 @@ typedef struct BlockNumber lastblock; BlockNumber currentblock; int64 ntuples; + int workers_attached; + int workers_expected; + BlockNumber num_blocks_per_worker; } ParallelCountInfo; +int ParallelWorkerNumber; + void _PG_init(void); void sleep_worker_main(dsm_segment *seg, shm_toc *toc); void count_worker_main(dsm_segment *seg, shm_toc *toc); @@ -122,6 +127,9 @@ parallel_count(PG_FUNCTION_ARGS) info->lastblock = RelationGetNumberOfBlocks(rel); info->currentblock = 0; info->ntuples = 0; + info->workers_attached = 0; + info->workers_expected = nworkers; + info->num_blocks_per_worker = info->lastblock / (nworkers + 1); shm_toc_insert(pcxt->toc, PARALLEL_DUMMY_KEY, info); LaunchParallelWorkers(pcxt); @@ -175,32 +183,35 @@ count_helper(Relation rel, ParallelCountInfo *info) int64 mytuples = 0; Oid relid = info->relid; Snapshot snapshot = GetActiveSnapshot(); - - for (;;) + BlockNumber blkno; + BlockNumber end_block; + BlockNumber start_block; + Buffer buffer; + Page page; + int lines; + OffsetNumber lineoff; + ItemId lpp; + bool all_visible; + + + SpinLockAcquire(&info->mutex); + ParallelWorkerNumber = info->workers_attached++; + SpinLockRelease(&info->mutex); + + end_block = (ParallelWorkerNumber + 1) * info->num_blocks_per_worker; + start_block = end_block - info->num_blocks_per_worker; + + /* + * Last worker is responsible for scanning all the remaining + * blocks in relation. + */ + if (ParallelWorkerNumber == info->workers_expected) + end_block = info->lastblock; + + for (blkno = start_block; blkno < end_block; blkno++) { - BlockNumber blkno; - Buffer buffer; - Page page; - int lines; - OffsetNumber lineoff; - ItemId lpp; - bool all_visible; - bool done = false; - CHECK_FOR_INTERRUPTS(); - SpinLockAcquire(&info->mutex); - if (info->currentblock >= info->lastblock) - done = true; - else - blkno = info->currentblock++; - info->ntuples += ntuples; - SpinLockRelease(&info->mutex); - - mytuples += ntuples; - if (done) - break; - buffer = ReadBuffer(rel, blkno); LockBuffer(buffer, BUFFER_LOCK_SHARE); page = BufferGetPage(buffer); @@ -210,8 +221,8 @@ count_helper(Relation rel, ParallelCountInfo *info) all_visible = PageIsAllVisible(page) && !snapshot->takenDuringRecovery; for (lineoff = FirstOffsetNumber, lpp = PageGetItemId(page, lineoff); - lineoff <= lines; - lineoff++, lpp++) + lineoff <= lines; + lineoff++, lpp++) { HeapTupleData loctup; @@ -232,6 +243,12 @@ count_helper(Relation rel, ParallelCountInfo *info) } UnlockReleaseBuffer(buffer); + + SpinLockAcquire(&info->mutex); + info->ntuples += ntuples; + SpinLockRelease(&info->mutex); + + mytuples += ntuples; } elog(NOTICE, "PID %d counted " INT64_FORMAT " tuples", MyProcPid, mytuples);