From 0e811309902e99c40159f0984d1e1dccfd419861 Mon Sep 17 00:00:00 2001
From: Kyotaro Horiguchi <horiguchi.kyotaro@lab.ntt.co.jp>
Date: Tue, 25 Jul 2017 17:19:10 +0900
Subject: [PATCH 5/5] Refactor ExecAsyncEventLoop

The compaction loop in ExecAsyncEventLoop was written in a bit tricky
way. This patch rewrites it in a more straight-forward way. Maybe.
---
 src/backend/executor/execAsync.c | 34 ++++++++++++++++++++++------------
 1 file changed, 22 insertions(+), 12 deletions(-)

diff --git a/src/backend/executor/execAsync.c b/src/backend/executor/execAsync.c
index 115b147..173ee39 100644
--- a/src/backend/executor/execAsync.c
+++ b/src/backend/executor/execAsync.c
@@ -222,28 +222,38 @@ ExecAsyncEventLoop(EState *estate, PlanState *requestor, long timeout)
 		/* If any node completed, compact the array. */
 		if (any_node_done)
 		{
-			int		hidx = 0,
-					tidx;
+			int		i = 0;
+			int		npending = 0;
 
 			/*
 			 * Swap all non-yet-completed items to the start of the array.
 			 * Keep them in the same order.
 			 */
-			for (tidx = 0; tidx < estate->es_num_pending_async; ++tidx)
+			/* Step 1: skip over not-completed elements at the beginning */
+			while (npending < estate->es_num_pending_async &&
+				   estate->es_pending_async[npending]->state !=
+				   ASYNCREQ_COMPLETE)
+				npending++;
+
+			/* Step 2: move forward not-completed elements hereafter */
+			for (i = npending + 1; i < estate->es_num_pending_async; ++i)
 			{
-				PendingAsyncRequest *head;
-				PendingAsyncRequest *tail = estate->es_pending_async[tidx];
+				PendingAsyncRequest *tmp;
+				PendingAsyncRequest *curr = estate->es_pending_async[i];
 
-				Assert(tail->state != ASYNCREQ_CALLBACK_PENDING);
+				Assert(curr->state != ASYNCREQ_CALLBACK_PENDING);
 
-				if (tail->state == ASYNCREQ_COMPLETE)
+				if (curr->state == ASYNCREQ_COMPLETE)
 					continue;
-				head = estate->es_pending_async[hidx];
-				estate->es_pending_async[tidx] = head;
-				estate->es_pending_async[hidx] = tail;
-				++hidx;
+
+				tmp = estate->es_pending_async[npending];
+				estate->es_pending_async[npending] =
+					estate->es_pending_async[i];
+				estate->es_pending_async[i] = tmp;
+				++npending;
 			}
-			estate->es_num_pending_async = hidx;
+
+			estate->es_num_pending_async = npending;
 		}
 
 		/*
-- 
2.9.2

