github.com/dubbogo/gost@v1.14.0/sync/connection_pool.go (about)

     1  /*
     2   * Licensed to the Apache Software Foundation (ASF) under one or more
     3   * contributor license agreements.  See the NOTICE file distributed with
     4   * this work for additional information regarding copyright ownership.
     5   * The ASF licenses this file to You under the Apache License, Version 2.0
     6   * (the "License"); you may not use this file except in compliance with
     7   * the License.  You may obtain a copy of the License at
     8   *
     9   *     http://www.apache.org/licenses/LICENSE-2.0
    10   *
    11   * Unless required by applicable law or agreed to in writing, software
    12   * distributed under the License is distributed on an "AS IS" BASIS,
    13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    14   * See the License for the specific language governing permissions and
    15   * limitations under the License.
    16   */
    17  
    18  package gxsync
    19  
    20  import (
    21  	"math/rand"
    22  	"sync/atomic"
    23  )
    24  
    25  import (
    26  	perrors "github.com/pkg/errors"
    27  )
    28  
    29  var (
    30  	PoolBusyErr = perrors.New("pool is busy")
    31  )
    32  
    33  func NewConnectionPool(config WorkerPoolConfig) WorkerPool {
    34  	return &ConnectionPool{
    35  		baseWorkerPool: newBaseWorkerPool(config),
    36  	}
    37  }
    38  
    39  type ConnectionPool struct {
    40  	*baseWorkerPool
    41  }
    42  
    43  func (p *ConnectionPool) Submit(t task) error {
    44  	if t == nil {
    45  		return perrors.New("task shouldn't be nil")
    46  	}
    47  
    48  	if !p.enable {
    49  		go t()
    50  		return nil
    51  	}
    52  
    53  	// put the task to a queue using Round Robin algorithm
    54  	taskId := atomic.AddUint32(&p.taskId, 1)
    55  	select {
    56  	case p.taskQueues[int(taskId)%len(p.taskQueues)] <- t:
    57  		return nil
    58  	default:
    59  	}
    60  
    61  	// put the task to a random queue with a maximum of len(p.taskQueues)/2 attempts
    62  	for i := 0; i < len(p.taskQueues)/2; i++ {
    63  		select {
    64  		case p.taskQueues[rand.Intn(len(p.taskQueues))] <- t:
    65  			return nil
    66  		default:
    67  			continue
    68  		}
    69  	}
    70  
    71  	return PoolBusyErr
    72  }
    73  
    74  func (p *ConnectionPool) SubmitSync(t task) error {
    75  	done := make(chan struct{})
    76  	fn := func() {
    77  		defer close(done)
    78  		t()
    79  	}
    80  
    81  	if err := p.Submit(fn); err != nil {
    82  		return err
    83  	}
    84  
    85  	<-done
    86  	return nil
    87  }