GF Framework grpool– High-performance Goroutine pool

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Grpool

Although goroutine in the go language is relatively lightweight compared to the system threads, the frequent creation and destruction of goroutine under high concurrency is also very stressful for performance loss and GC. Full reuse of the goroutine reduces the performance loss of goroutine creation/destruction, which is the grpool of goroutine for pooling encapsulation purposes. For example, in order to perform tasks in 100W, the use of goroutine requires the creation and destruction of 100W goroutine, while the use of Grpool may require only thousands of goroutine at the bottom to fully re-use to perform all tasks. After testing, the performance of Grpool in high concurrency is several to hundreds of times times higher than that of native Goroutine! And it also greatly reduces memory usage.

Performance test report: Http://johng.cn/grpool-perfor ...

Method List

func Add(f func())func Jobs() intfunc SetExpire(expire int)func SetSize(size int)func Size() inttype Pool    func New(expire int, sizes ...int) *Pool    func (p *Pool) Add(f func())    func (p *Pool) Close()    func (p *Pool) Jobs() int    func (p *Pool) SetExpire(expire int)    func (p *Pool) SetSize(size int)    func (p *Pool) Size() int

Through Grpool. The new method creates a goroutine pool with a time in seconds for the goroutine in the given pool, and the second parameter is a non-required parameter that limits the number of work goroutine in the pool, which is not limited by default. It is important to note that tasks can be added to the pool without restrictions, but the goroutine of work can be limited. We can query the current number of work goroutine through the size () method and use the jobs () method to query the number of tasks to be processed in the current pool.

At the same time, the size and goroutine validity of the pool can be dynamically changed at run time through the SetSize and Setexpire methods. This feature makes the management of the pool more flexible, but it also increases the risk of maintenance because you do not know where the properties of the pools have been modified.

At the same time, for ease of use, the Grpool package provides the default Goroutine pool, directly through the Grpool. Add to the default pool, the task parameter must be a func () type of function/method.

Using the example

1, use the default Goroutine pool, limit 10 work Goroutine perform 1000 tasks.

Https://gitee.com/johng/gf/bl ...

package mainimport (    "time"    "fmt"    "gitee.com/johng/gf/g/os/gtime"    "gitee.com/johng/gf/g/os/grpool")func job() {    time.Sleep(1*time.Second)}func main() {    grpool.SetSize(10)    for i := 0; i < 1000; i++ {        grpool.Add(job)    }    gtime.SetInterval(2*time.Second, func() bool {        fmt.Println("size:", grpool.Size())        fmt.Println("jobs:", grpool.Jobs())        return true    })    select {}}

The function of the task function in this program is to sleep for 1 seconds, so as to fully demonstrate the Goroutine number limit function. Among them, we used the gtime. The setinterval timer prints out the number of work Goroutine in the current default pool and the number of tasks to be processed every 2 seconds.

2. Let's look at an example of a novice who is often prone to error

Https://gitee.com/johng/gf/bl ...

package mainimport (    "fmt"    "sync"    "gitee.com/johng/gf/g/os/grpool")func main() {    wg := sync.WaitGroup{}    for i := 0; i < 10; i++ {        wg.Add(1)        grpool.Add(func() {            fmt.Println(i)            wg.Done()        })    }    wg.Wait()}

The purpose of our code is to print 0-9 sequentially, but after running it outputs:

10101010101010101010

Why is it? The execution results here are performed either with the Go keyword or grpool. The reason is that, for asynchronous thread/coprocessor, when a function performs an asynchronous registration, the function does not actually start executing (only the memory address of the variable i is stored in the Goroutine stack at the time of registration), and the function will read the value of the variable I once the execution is started. At this point the value of the variable i has been increased from 10.
After the reason is clear, the improvement scheme is also very simple, that is, when registering the asynchronous execution function, the value of the variable i is also passed to get, or the current variable i is assigned to a temporary variable that does not change, use the temporary variable in the function instead of directly using the variable i.

The improved sample code is as follows:

1), use the GO keyword

Https://gitee.com/johng/gf/bl ...

package mainimport (    "fmt"    "sync")func main() {    wg := sync.WaitGroup{}    for i := 0; i < 10; i++ {        wg.Add(1)        go func(v int){            fmt.Println(v)            wg.Done()        }(i)    }    wg.Wait()}

After execution, the output is:

9012345678

Note that asynchronous execution is not guaranteed to be executed in the order in which the function is registered, as in the following.

2), using temporary variables

Https://gitee.com/johng/gf/bl ...

package mainimport (    "fmt"    "sync"    "gitee.com/johng/gf/g/os/grpool")func main() {    wg := sync.WaitGroup{}    for i := 0; i < 10; i++ {        wg.Add(1)        v := i        grpool.Add(func() {            fmt.Println(v)            wg.Done()        })    }    wg.Wait()}

After execution, the output is:

9012345678

As you can see here, you can only use the Func () type parameter when using Grpool for task registration, so you cannot register the value of the variable I in the task registration, so you can only pass the value of the current variable I in the form of a temporary variable.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.