go-hep.org/x/hep@v0.38.1/hplot/htex/handler.go (about)

     1  // Copyright ©2020 The go-hep Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package htex
     6  
     7  import (
     8  	"runtime"
     9  
    10  	"golang.org/x/sync/errgroup"
    11  )
    12  
    13  // GoHandler is a Latex handler that compiles
    14  // Latex document in background goroutines.
    15  type GoHandler struct {
    16  	ch   chan int // throttling channel
    17  	grp  *errgroup.Group
    18  	hdlr Handler
    19  }
    20  
    21  // NewGoHandler creates a new Latex handler that compiles Latex
    22  // document in the background with the cmd executable.
    23  //
    24  // The handler allows for up to n concurrent compilations.
    25  // If n<=0, the concurrency will be set to the number of cores+1.
    26  func NewGoHandler(n int, cmd string) *GoHandler {
    27  	if n <= 0 {
    28  		n = runtime.NumCPU() + 1
    29  	}
    30  
    31  	h := &GoHandler{
    32  		ch:   make(chan int, n),
    33  		grp:  new(errgroup.Group),
    34  		hdlr: NewHandler(cmd),
    35  	}
    36  
    37  	return h
    38  }
    39  
    40  // CompileLatex compiles the provided .tex document.
    41  func (gh *GoHandler) CompileLatex(fname string) error {
    42  	gh.grp.Go(func() error {
    43  		gh.ch <- 1
    44  		defer func() { <-gh.ch }()
    45  		return gh.hdlr.CompileLatex(fname)
    46  	})
    47  	return nil
    48  }
    49  
    50  func (gh *GoHandler) Wait() error {
    51  	return gh.grp.Wait()
    52  }