🚀 Golang

安装go

1 下载 官网 wget https://go.dev/dl/go1.21.5.linux-amd64.tar.gz 2 配置 移除之前的安装版本 rm -rf /usr/local/go && tar -C /usr/local -xzf go1.21.5.linux-amd64.tar.gz 添加环境 vim /etc/profile # or vim $HOME/.profile export GOROOT=/usr/local/go export PATH=$PATH:$GOROOT/bin source /etc/profile # or source $HOME/.profile 查看版本 go version 设置代理 go env -w GOPROXY=https://goproxy.cn,direct 3 go版本管理器 gvm

更多 →

August 29, 2024

pprof

引入依赖 import _ "net/http/pprof" 分析内存 go tool pprof http://localhost:8081/debug/pprof/heap 分析CPU go tool pprof http://localhost:8081/debug/pprof/profile File: ___3go_build_lattice_manager_grpc_cmd_server Type: cpu Time: Jul 31, 2024 at 10:15am (CST) Duration: 30.10s, Total samples = 100ms ( 0.33%) Entering interactive mode (type "help" for commands, "o" for options) (pprof) top Showing nodes accounting for 100ms, 100% of 100ms total Showing top 10 nodes out of 125 flat flat% sum% cum cum% 20ms 20.00% 20.00% 20ms 20.

更多 →

July 31, 2024

GMP 模型

1.前言 1.1 线程模型 内核级线程(Kernel Level Thread)模型 用户级线程(User Level Thread)模型 两级线程模型(混合型线程模型) 1.2 ULT vs KLT 特性 用户级线程 内核级线程 创建者 应用程序 内核 操作系统是否感知存在 否 是 开销成本 创建成本低,上下文切换成本低,上下文切换不需要硬件支持。 创建成本高,上下文切换成本高,上下文切换需要硬件支持。 如果线程阻塞 整个进程将被阻塞,即不能利用多处理来发挥并发优势。 其它线程可以继续执行,进程不会阻塞。 案例 Java thread,POSIX threads Windows Solaris 1.3 内核级线程模型 内核级线程模型中用户线程与内核线程是一对一关系(1 : 1)。线程的创建、销毁、切换工作都是有内核完成的。应用程序不参与线程的管理工作,只能调用内核级线程编程接口(应用程序创建一个新线程或撤销一个已有线程时,都会进行一个系统调用)。每个用户线程都会被绑定到一个内核线程。用户线程在其生命期内都会绑定到该内核线程。一旦用户线程终止,两个线程都将离开系统。 1.4 用户级线程模型 用户线程模型中的用户线程与内核线程KSE是多对一关系(N : 1)。线程的创建、销毁以及线程之间的协调、同步等工作都是在用户态完成,具体来说就是由应用程序的线程库来完成。内核对这些是无感知的,内核此时的调度都是基于进程的。线程的并发处理从宏观来看,任意时刻每个进程只能够有一个线程在运行,且只有一个处理器内核会被分配给该进程。 1.5 两级线程模型 两级线程模型中用户线程与内核线程是一对一关系(N : M)。两级线程模型充分吸收上面两种模型的优点,尽量规避缺点。其线程创建在用户空间中完成,线程的调度和同步也在应用程序中进行。一个应用程序中的多个用户级线程被绑定到一些(小于或等于用户级线程的数目)内核级线程上。 1.6 Golang 线程模型 Golang在底层实现了混合型线程模型。M 即系统线程,由系统调用产生,一个M关联一个 KSE,即两级线程模型中的系统线程。G 为 Groutine,即两级线程模型的的应用及线程。M 与 G 的关系是 N:M。 Golang线程模型与GMP 2.GMP G(Goroutine):代表 Go 协程 Goroutine,存储了 Goroutine 的执行栈信息、Goroutine 状态以及 Goroutine 的任务函数等。G 的数量无限制,理论上只受内存影响,创建了一个 G 的初始栈大小为 2~4K,配置一般的机器也能简单开启数十万个 Goroutine,而且 Go 语言在 G 退出的时候还会把 G 清理之后放到 P 本地或者全局的闲置列表 gFree 中以便复用。

更多 →

April 14, 2024

Context

更多 →

March 1, 2024

Goroutines and Channels

A goroutine is a lightweight thread managed by the Go runtime. Channels is how you communicate between routines. 1.Goroutines Concurrency, what’s the benefit Concurrency is the task of running and managing the multiple computations at the same time. While parallelism is the task of running multiple computations simultaneously. So what are some benefits: Faster processing. The benefit is getting tasks done faster. Imagine that you are searching a computer for files, or processing data, if it’s possible to work on these workloads in parallel, you end up getting the response back faster.

更多 →

March 1, 2024

CGO

#go#cgo

CGO

更多 →

February 19, 2024