From b971e97474415c81c4cd1919b86fd24245df6008 Mon Sep 17 00:00:00 2001 From: laishenghao Date: Tue, 27 Jun 2023 20:52:00 +0800 Subject: [PATCH] =?UTF-8?q?=E8=A7=A3=E5=86=B3=E5=B9=B6=E8=A1=8C=E5=88=9B?= =?UTF-8?q?=E5=BB=BA=E7=B4=A2=E5=BC=95=E5=87=BA=E7=8E=B0=E8=AD=A6=E5=91=8A?= =?UTF-8?q?=E6=97=A5=E5=BF=97=E7=9A=84=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../process/postmaster/bgworker.cpp | 43 +++++++++++++++++-- 1 file changed, 39 insertions(+), 4 deletions(-) diff --git a/src/gausskernel/process/postmaster/bgworker.cpp b/src/gausskernel/process/postmaster/bgworker.cpp index bcb5522d0..e9a3dc917 100644 --- a/src/gausskernel/process/postmaster/bgworker.cpp +++ b/src/gausskernel/process/postmaster/bgworker.cpp @@ -364,6 +364,7 @@ bool RegisterBackgroundWorker(BgWorkerContext *bwc) BGW_HDR* bgworker_base = (BGW_HDR *)g_instance.bgw_base; BackgroundWorker *bgw = NULL; BackgroundWorkerArgs *bwa = NULL; + Backend* bn = nullptr; /* Construct bgworker thread args */ bwa = (BackgroundWorkerArgs*)MemoryContextAllocZero( @@ -387,15 +388,49 @@ bool RegisterBackgroundWorker(BgWorkerContext *bwc) bwa->bgworker = bgw; bwa->bgworkerId = bgw->bgw_id; - /* Fork a new worker thread */ - bgw->bgw_notify_pid = initialize_util_thread(BGWORKER, bwa); - /* failed to fork a new thread */ - if (bgw->bgw_notify_pid == 0) { + int slot = AssignPostmasterChildSlot(); + if (slot == -1) { pfree_ext(bwa); BgworkerPutBackToFreeList(bgw); return false; } + bn = AssignFreeBackEnd(slot); + int thisChildSlot = t_thrd.proc_cxt.MyPMChildSlot; + if (bn) { + GenerateCancelKey(false); + bn->cancel_key = t_thrd.proc_cxt.MyCancelKey; + bn->child_slot = t_thrd.proc_cxt.MyPMChildSlot = slot; + bn->role = BGWORKER; + } else { + ReleasePostmasterChildSlot(slot); + pfree_ext(bwa); + BgworkerPutBackToFreeList(bgw); + ereport(LOG, (errcode(ERRCODE_LOG), errmsg("assign backend failed in RegisterBackgroundWorker"))); + return false; + } + + /* Fork a new worker thread */ + bgw->bgw_notify_pid = initialize_util_thread(BGWORKER, bwa); + t_thrd.proc_cxt.MyPMChildSlot = thisChildSlot; + + /* failed to fork a new thread */ + if (bgw->bgw_notify_pid == 0) { + pfree_ext(bwa); + BgworkerPutBackToFreeList(bgw); + ReleasePostmasterChildSlot(slot); + + bn->pid = 0; + bn->role = (knl_thread_role)0; + bn = nullptr; + return false; + } + + bn->pid = bgw->bgw_notify_pid; + bn->is_autovacuum = false; + DLInitElem(&bn->elem, bn); + DLAddHead(g_instance.backend_list, &bn->elem); + if (g_threadPoolControler) { // Try to bind thread to available CPUs in threadpool g_threadPoolControler->BindThreadToAllAvailCpu(bgw->bgw_notify_pid);