github.com/alibaba/ilogtail/pkg@v0.0.0-20250526110833-c53b480d046c/pipeline/control.go (about)

     1  // Copyright 2022 iLogtail Authors
     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 pipeline
    16  
    17  import "sync"
    18  
    19  // AsyncControl is an asynchronous execution control that can be canceled.
    20  type AsyncControl struct {
    21  	cancelToken chan struct{}
    22  	wg          sync.WaitGroup
    23  }
    24  
    25  // CancelToken returns a readonly channel that can be subscribed to as a cancel token
    26  func (p *AsyncControl) CancelToken() <-chan struct{} {
    27  	return p.cancelToken
    28  }
    29  
    30  func (p *AsyncControl) Notify() {
    31  	p.cancelToken <- struct{}{}
    32  }
    33  
    34  // Reset cancel channal
    35  func (p *AsyncControl) Reset() {
    36  	if p.cancelToken == nil {
    37  		p.cancelToken = make(chan struct{}, 1)
    38  	}
    39  }
    40  
    41  // Run function as a Task
    42  func (p *AsyncControl) Run(task func(*AsyncControl)) {
    43  	p.wg.Add(1)
    44  	go func(cc *AsyncControl, fn func(*AsyncControl)) {
    45  		defer cc.wg.Done()
    46  		fn(cc)
    47  	}(p, task)
    48  }
    49  
    50  // Waiting for executing task to be canceled
    51  func (p *AsyncControl) WaitCancel() {
    52  	close(p.cancelToken)
    53  	p.wg.Wait()
    54  	p.cancelToken = nil
    55  }
    56  
    57  func NewAsyncControl() *AsyncControl {
    58  	return &AsyncControl{
    59  		cancelToken: make(chan struct{}, 1),
    60  	}
    61  }