github.com/bytedance/gopkg@v0.0.0-20240514070511-01b2cbcf35e1/util/gopool/worker.go (about)

     1  // Copyright 2021 ByteDance Inc.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package gopool
    16  
    17  import (
    18  	"fmt"
    19  	"runtime/debug"
    20  	"sync"
    21  	"sync/atomic"
    22  
    23  	"github.com/bytedance/gopkg/util/logger"
    24  )
    25  
    26  var workerPool sync.Pool
    27  
    28  func init() {
    29  	workerPool.New = newWorker
    30  }
    31  
    32  type worker struct {
    33  	pool *pool
    34  }
    35  
    36  func newWorker() interface{} {
    37  	return &worker{}
    38  }
    39  
    40  func (w *worker) run() {
    41  	go func() {
    42  		for {
    43  			var t *task
    44  			w.pool.taskLock.Lock()
    45  			if w.pool.taskHead != nil {
    46  				t = w.pool.taskHead
    47  				w.pool.taskHead = w.pool.taskHead.next
    48  				atomic.AddInt32(&w.pool.taskCount, -1)
    49  			}
    50  			if t == nil {
    51  				// if there's no task to do, exit
    52  				w.close()
    53  				w.pool.taskLock.Unlock()
    54  				w.Recycle()
    55  				return
    56  			}
    57  			w.pool.taskLock.Unlock()
    58  			func() {
    59  				defer func() {
    60  					if r := recover(); r != nil {
    61  						if w.pool.panicHandler != nil {
    62  							w.pool.panicHandler(t.ctx, r)
    63  						} else {
    64  							msg := fmt.Sprintf("GOPOOL: panic in pool: %s: %v: %s", w.pool.name, r, debug.Stack())
    65  							logger.CtxErrorf(t.ctx, msg)
    66  						}
    67  					}
    68  				}()
    69  				t.f()
    70  			}()
    71  			t.Recycle()
    72  		}
    73  	}()
    74  }
    75  
    76  func (w *worker) close() {
    77  	w.pool.decWorkerCount()
    78  }
    79  
    80  func (w *worker) zero() {
    81  	w.pool = nil
    82  }
    83  
    84  func (w *worker) Recycle() {
    85  	w.zero()
    86  	workerPool.Put(w)
    87  }