github.com/alphadose/itogami@v0.4.1-0.20221016160904-c25d0a36bfe7/examples/main.go (about)

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  	"sync"
     6  	"sync/atomic"
     7  	"time"
     8  
     9  	"github.com/alphadose/itogami"
    10  )
    11  
    12  const runTimes uint32 = 1000
    13  
    14  var sum uint32
    15  
    16  func myFunc(i uint32) {
    17  	atomic.AddUint32(&sum, i)
    18  	fmt.Printf("run with %d\n", i)
    19  }
    20  
    21  func demoFunc() {
    22  	time.Sleep(10 * time.Millisecond)
    23  	println("Hello World")
    24  }
    25  
    26  func examplePool() {
    27  	var wg sync.WaitGroup
    28  	// Use the common pool
    29  	pool := itogami.NewPool(10)
    30  
    31  	syncCalculateSum := func() {
    32  		demoFunc()
    33  		wg.Done()
    34  	}
    35  	for i := uint32(0); i < runTimes; i++ {
    36  		wg.Add(1)
    37  		// Submit task to the pool
    38  		pool.Submit(syncCalculateSum)
    39  	}
    40  	wg.Wait()
    41  	println("finished all tasks")
    42  }
    43  
    44  func examplePoolWithFunc() {
    45  	var wg sync.WaitGroup
    46  	// Use the pool with a pre-defined function
    47  	pool := itogami.NewPoolWithFunc(10, func(i uint32) {
    48  		myFunc(i)
    49  		wg.Done()
    50  	})
    51  	for i := uint32(0); i < runTimes; i++ {
    52  		wg.Add(1)
    53  		// Invoke the function with a value
    54  		pool.Invoke(i)
    55  	}
    56  	wg.Wait()
    57  	fmt.Printf("finish all tasks, result is %d\n", sum)
    58  }
    59  
    60  func main() {
    61  	examplePool()
    62  	examplePoolWithFunc()
    63  }