zoukankan      html  css  js  c++  java
  • Go 典型并发任务

    学习-极客时间-Go语言从入门到实战 笔记

    单例模式

    代码片段举例:

    package once
    
    import (
    	"fmt"
    	"sync"
    	"testing"
    	"unsafe"
    )
    
    type Movie struct {
    }
    
    var once sync.Once
    var SingleInstance *Movie
    
    func GetInstance() *Movie {
    	once.Do(func() {
    		fmt.Println("create instance")
    		SingleInstance = new(Movie)
    	})
    	return SingleInstance
    }
    
    func TestSingleInstance(t *testing.T) {
    	var wg sync.WaitGroup
    	for i := 0; i < 5; i++ {
    		wg.Add(1)
    		go func() {
    			sing := GetInstance()
    			fmt.Println(unsafe.Pointer(sing))
    			wg.Done()
    		}()
    	}
    	wg.Wait()
    }
    

    仅需任意任务完成

    代码片段举例:

    package only
    
    import (
    	"fmt"
    	"runtime"
    	"testing"
    	"time"
    )
    
    func runTask(id int) string {
    	time.Sleep(10 * time.Millisecond)
    	return fmt.Sprintf("The result is from %d", id)
    }
    
    func FirstResponse() string {
    	numOfRunner := 10
    	ch := make(chan string, numOfRunner)
    	//没有指定channel容量,会导致阻塞,channel等待接收者,协程泄漏
    	//ch := make(chan string)
    	for i := 0; i < numOfRunner; i++ {
    		go func(i int) {
    			ch <- runTask(i)
    		}(i)
    	}
    	return <-ch
    }
    
    func TestOnly(t *testing.T) {
    	t.Log("Before: ", runtime.NumGoroutine())
    	fmt.Println(FirstResponse())
    	time.Sleep(time.Second * 1)
    	t.Log("After: ", runtime.NumGoroutine())
    }
    

    所有任务完成

    代码片段举例:

    package all
    
    import (
    	"fmt"
    	"runtime"
    	"testing"
    	"time"
    )
    
    func runTask(id int) string {
    	time.Sleep(10 * time.Millisecond)
    	return fmt.Sprintf("The result is from %d", id)
    }
    
    func FirstResponse() string {
    	numOfRunner := 10
    	ch := make(chan string, numOfRunner)
    	//没有指定channel容量,会导致阻塞,channel等待接收者,协程泄漏
    	//ch := make(chan string)
    	for i := 0; i < numOfRunner; i++ {
    		go func(i int) {
    			ch <- runTask(i)
    		}(i)
    	}
    	res := ""
    	for j := 0; j < numOfRunner; j++ {
    		res += <-ch + "
    "
    	}
    	return res
    }
    
    func TestOnly(t *testing.T) {
    	t.Log("Before: ", runtime.NumGoroutine())
    	fmt.Println(FirstResponse())
    	time.Sleep(time.Second * 1)
    	t.Log("After: ", runtime.NumGoroutine())
    }
    
  • 相关阅读:
    BZOJ1050: [HAOI2006]旅行comf(并查集 最小生成树)
    洛谷P1762 偶数(找规律)
    抽象类的基本概念------abstract
    百度地图小图标没有显示的解决方案
    nfs:server 172.168.1.22 not responding,still trying问题解决方法 平台为RealARM 210平台
    大话分页(二)
    In App Purchases(IAP 应用程序內购买): 完全攻略
    快速修改数组的问题
    64位linux中使用inet_ntoa报错处理
    CDN和双线机房相比有何优势
  • 原文地址:https://www.cnblogs.com/yangqi7/p/12425594.html
Copyright © 2011-2022 走看看