Example #1
2
func main() {
	_, err := OutFunc()
	if err != nil {
		log.Printf("error is : %v", err)
	}
	fmt.Printf("End of main")

	data := []int{0, 1, 2, 3, 4}
	s1 := data[:2]
	fmt.Printf("data ptr is %p, s1 ptr is %p", &data, &s1)
	s2 := append(s1, 100, 200)
	fmt.Println("\n", data)
	fmt.Println(s1)
	fmt.Println(s2)
	fmt.Printf("data ptr is %p, s1 ptr is %p, s2 ptr is %p \n", &data, &s1, &s2)

	var pool *sync.Pool
	pool = new(sync.Pool)
	pool.New = func() interface{} {
		return 1
	}
	//pool.Put(1)
	i := pool.Get()
	if i == nil {
		fmt.Println("pool.Get is non-block function. nil could be returned. not cool")
	} else {
		fmt.Println("number is ", i)
	}

}
Example #2
0
func main() {
	// 禁用GC,并保证在main函数执行结束前恢复GC
	defer debug.SetGCPercent(debug.SetGCPercent(-1))
	var count int32
	newFunc := func() interface{} {
		return atomic.AddInt32(&count, 1)
	}
	pool := sync.Pool{New: newFunc}

	// New 字段值的作用
	v1 := pool.Get()
	fmt.Printf("v1: %v\n", v1)

	// 临时对象池的存取
	pool.Put(newFunc())
	pool.Put(newFunc())
	pool.Put(newFunc())
	v2 := pool.Get()
	fmt.Printf("v2: %v\n", v2)

	// 垃圾回收对临时对象池的影响
	debug.SetGCPercent(100)
	runtime.GC()
	v3 := pool.Get()
	fmt.Printf("v3: %v\n", v3)
	pool.New = nil
	v4 := pool.Get()
	fmt.Printf("v4: %v\n", v4)
}
Example #3
0
func Gzip(level int) gin.HandlerFunc {
	var gzPool sync.Pool
	gzPool.New = func() interface{} {
		gz, err := gzip.NewWriterLevel(ioutil.Discard, level)
		if err != nil {
			panic(err)
		}
		return gz
	}
	return func(c *gin.Context) {
		if !shouldCompress(c.Request) {
			return
		}

		gz := gzPool.Get().(*gzip.Writer)
		defer gzPool.Put(gz)
		gz.Reset(c.Writer)

		c.Header("Content-Encoding", "gzip")
		c.Header("Vary", "Accept-Encoding")
		c.Writer = &gzipWriter{c.Writer, gz}
		defer func() {
			c.Header("Content-Length", "0")
			gz.Close()
		}()
		c.Next()
	}
}
Example #4
0
func NewByteSlicePool(size int) *ByteSlicePool {
	p := new(sync.Pool)
	p.New = func() interface{} {
		return make([]byte, size)
	}

	return &ByteSlicePool{p}
}
Example #5
0
func newBufferPool() *bufferPool {
	var p sync.Pool
	p.New = func() interface{} {
		return make([]byte, 20480)
	}

	return &bufferPool{p}
}
Example #6
0
func NewMPool(sz int) *MPool {
	p := &MPool{sz: sz}
	pool := new(sync.Pool)
	pool.New = func() interface{} {
		buf := make([]byte, p.sz)
		atomic.AddInt32(&p.alloced, 1)
		return buf
	}
	p.pool = pool
	return p
}
Example #7
0
func main() {
	var pool sync.Pool
	pool.New = func() interface{} {
		return person{name: "name", timestamp: time.Now()}
	}
	var p, q, r person

	p = pool.Get().(person)
	fmt.Println(p.timestamp.String())
	pool.Put(p)
	r = pool.Get().(person)
	q = pool.Get().(person)
	fmt.Println(r.timestamp.String())
	fmt.Println(q.timestamp.String())

}
Example #8
0
File: main.go Project: oywc410/MYPG
func test1() {
	//Pool内存缓存 GC时将被清除

	var bp sync.Pool
	var looks sync.RWMutex
	bp.New = func() interface{} {
		return &bytes.Buffer{}
	}

	buf := bp.Get().(*bytes.Buffer)
	buf.WriteString("test")
	fmt.Println(buf.String())
	bp.Put(buf) //记录至缓存

	limit := make(chan struct{}, 10)

	go func() {
		buf := bp.Get().(*bytes.Buffer)
		buf.WriteString("tttt")
		looks.Lock()
		bp.Put(buf)
		looks.Unlock()
	}()
	time.Sleep(1 * time.Second)
	for {
		limit <- struct{}{}
		go func() {
			//提取以后必须再次Put 否则将被清除
			buf := bp.Get().(*bytes.Buffer)
			if buf.Len() != 0 {
				fmt.Println(buf.String())
				looks.Lock()
				bp.Put(buf)
				looks.Unlock()
				//runtime.GC()
			}
			<-limit
		}()
	}

	return
	runtime.GC() //手动启动GC

	buf = bp.Get().(*bytes.Buffer) //由于缓存被清空 反问内容为空
	fmt.Println(buf.String())
}
Example #9
0
// Handle provides on-the-fly gzip encoding for other handlers.
//
// Usage:
//
//	func DL1Handler(w http.ResponseWriter, req *http.Request) {
//		fmt.Fprintln(w, "foobar")
//	}
//
//	func DL2Handler(w http.ResponseWriter, req *http.Request) {
//		fmt.Fprintln(w, "zzz")
//	}
//
//
//	func main() {
//		http.HandleFunc("/download1", DL1Handler)
//		http.HandleFunc("/download2", DL2Handler)
//		http.ListenAndServe(":8080", Gzip(http.DefaultServeMux))
//	}
func Gzip(h http.Handler) http.HandlerFunc {
	var pool sync.Pool
	pool.New = func() interface{} {
		return gzip.NewWriter(ioutil.Discard)
	}
	return func(w http.ResponseWriter, r *http.Request) {
		// Do nothing on a HEAD request
		if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") || r.Method == "HEAD" ||
			w.Header().Get("Content-Encoding") == "gzip" { // Skip compression if already compressed

			h.ServeHTTP(w, r)
			return
		}
		w.Header().Set("Content-Encoding", "gzip")
		gz := pool.Get().(*gzip.Writer)
		defer pool.Put(gz)
		gz.Reset(w)

		h.ServeHTTP(IOResponseWriter{Writer: gz, ResponseWriter: WrapWriter(w)}, r)
		gz.Close()
	}
}
Example #10
0
func (sn *Node) GenSetPool() {
	var p sync.Pool
	p.New = NewSigningMessage
	sn.SetPool(&p)
}
Example #11
0
func startHTTPServer(hostport string, msgchs []chan<- msg, quit <-chan struct{}, wg *sync.WaitGroup) {
	var bufPool sync.Pool
	var msgPool sync.Pool
	msgPool.New = func() interface{} {
		return &msg{nil, make(chan error, 1)}
	}

	var rndPool sync.Pool
	rndPool.New = func() interface{} {
		return rand.New(rand.NewSource(time.Now().UnixNano()))
	}

	handler := func(w http.ResponseWriter, r *http.Request) {
		defer r.Body.Close()

		cl := int(r.ContentLength)
		if cl <= 0 {
			http.Error(w, http.StatusText(http.StatusLengthRequired), http.StatusLengthRequired)
			return
		}

		buf, ok := bufPool.Get().([]byte)
		if ok && cap(buf) < cl+16 { // + 16, in case of worker will need to encode object
			bufPool.Put(buf)
			buf = make([]byte, cl, cl+16)
		} else if ok {
			buf = buf[:cl]
		} else {
			buf = make([]byte, cl, cl+16)
		}

		defer bufPool.Put(buf)

		if _, err := io.ReadFull(r.Body, buf); err != nil {
			log.Println("HTTP server: failed to read body", err)
			http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
			return
		}

		msg := msgPool.Get().(*msg)
		defer msgPool.Put(msg)
		msg.buf = buf

		rnd := rndPool.Get().(*rand.Rand)
		defer rndPool.Put(rnd)

		msgchs[rnd.Intn(len(msgchs))] <- *msg
		if err := <-msg.err; err != nil {
			log.Println("HTTP server: failed to process message", err)
			http.Error(w, err.Error(), http.StatusBadRequest)
			return
		}
	}

	addr, err := net.ResolveTCPAddr("tcp4", hostport)
	if err != nil {
		log.Fatal("failed to resolve addr: ", err)
	}

	conn, err := net.ListenTCP("tcp4", addr)
	if err != nil {
		log.Fatal("failed to lister UDP socket: ", err)
	}

	http.HandleFunc("/", handler)
	srv := &http.Server{Addr: hostport}
	go func() {
		log.Println("starting HTTP server", hostport)

		wg.Add(1)
		defer wg.Done()

		srv.Serve(newStoppableListener(conn, quit))
	}()
}