zoukankan      html  css  js  c++  java
  • golang sync.pool

    这个例子,理解一下

    package main
    
    import (
    	"fmt"
    	"sync"
    	"time"
    )
    
    // Pool for our struct A
    var pool *sync.Pool
    
    // A dummy struct with a member 
    type A struct {
    	Name string
    }
    
    // Func to init pool
    func initPool() {
    	pool = &sync.Pool {
    		New: func()interface{} {
    			fmt.Println("Returning new A")
    			return new(A)
    		},
    	}
    }
    
    // Main func
    func main() {
    	// Initializing pool
    	initPool()
    	// Get hold of instance one
    	one := pool.Get().(*A)
    	one.Name = "first"
    	fmt.Printf("one.Name = %s
    ", one.Name)
    	// Pass one to a go routine that just stops for 10 second
    	// Assume that this could be any i/o bound task, something like an API call
    	go func(o *A) {
    		fmt.Printf("Before pool.Put
    o.Name = %s
    ", o.Name)
    		time.Sleep(10 * time.Second)
    		fmt.Printf("After pool.Put With same object
    o.Name = %s
    ", o.Name)
    	}(one)
    	// Main routine performs some operations for 1 second
    	time.Sleep(1 * time.Second)
    	// Till then your main routine submits back the main object
    	pool.Put(one)
    	two := pool.Get().(*A)
    	two.Name = "second"
    	fmt.Printf("two.Name = %s
    ", two.Name)
    	// Just for the sake of demo wait for next 15 seconds
    	time.Sleep(15 * time.Second)	
    }
    

      

  • 相关阅读:
    用JavaDoc生成项目文档
    thymeleaf参考手册
    转的一个Java基本功
    杂记
    修改Esxi克隆的CentOS的IP地址
    CentOS搭建socket5代理服务器
    CentOS上搭建Nginx + Mono 运行 asp.net
    启动PPT的时候一直配置vs2013的问题解决
    swift 元组
    swift 集合类型(二)
  • 原文地址:https://www.cnblogs.com/oxspirt/p/15357184.html
Copyright © 2011-2022 走看看