github.com/aacfactory/fns@v1.2.86-0.20240310083819-80d667fc0a17/commons/procs/procs.go (about)

     1  /*
     2   * Copyright 2023 Wang Min Xiang
     3   *
     4   * Licensed under the Apache License, Version 2.0 (the "License");
     5   * you may not use this file except in compliance with the License.
     6   * You may obtain a copy of the License at
     7   *
     8   * 	http://www.apache.org/licenses/LICENSE-2.0
     9   *
    10   * Unless required by applicable law or agreed to in writing, software
    11   * distributed under the License is distributed on an "AS IS" BASIS,
    12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13   * See the License for the specific language governing permissions and
    14   * limitations under the License.
    15   *
    16   */
    17  
    18  package procs
    19  
    20  import (
    21  	"go.uber.org/automaxprocs/maxprocs"
    22  	"runtime"
    23  )
    24  
    25  func New(min int) *AutoMaxProcs {
    26  	if min < 0 {
    27  		min = 0
    28  	}
    29  	return &AutoMaxProcs{
    30  		min:     min,
    31  		resetFn: nil,
    32  	}
    33  }
    34  
    35  type AutoMaxProcs struct {
    36  	min     int
    37  	max     int
    38  	resetFn func()
    39  }
    40  
    41  func (p *AutoMaxProcs) Enable() {
    42  	if p.min > 0 {
    43  		reset, setErr := maxprocs.Set(maxprocs.Min(p.min), maxprocs.Logger(func(s string, i ...interface{}) {}))
    44  		if setErr != nil {
    45  			runtime.GOMAXPROCS(0)
    46  			return
    47  		}
    48  		p.resetFn = reset
    49  	}
    50  	return
    51  }
    52  
    53  func (p *AutoMaxProcs) Reset() {
    54  	if p.resetFn != nil {
    55  		p.resetFn()
    56  	}
    57  }