修改golang源代码实现无竞争版ThreadLocal

开篇

书接上文 修改golang源代码获取goroutine id实现ThreadLocal。上文实现的版本由于map是多个goroutine共享的,存在竞争,影响了性能,实现思路类似java初期的ThreadLocal,今天我们借鉴现代版java的ThreadLocal来实现。

思路

先看看java里面怎么实现的


image.png

可以看到每个线程实例都引用了一个map,map的key是ThreadLocal对象,value是实际存储的数据。下面我们也按照这个思路来实现,golang中g实例相当于java的Thread实例,我们可以修改g的结构来达到目的。

实现

修改g结构

修改 $GOROOT/src/runtime/runtime2.go 文件,为g结构体添加 localMap *goroutineLocalMap 字段

type g struct {
    // Stack parameters.
    // stack describes the actual stack memory: [stack.lo, stack.hi).
    // stackguard0 is the stack pointer compared in the Go stack growth prologue.
    // It is stack.lo+StackGuard normally, but can be StackPreempt to trigger a preemption.
    // stackguard1 is the stack pointer compared in the C stack growth prologue.
    // It is stack.lo+StackGuard on g0 and gsignal stacks.
    // It is ~0 on other goroutine stacks, to trigger a call to morestackc (and crash).
    stack       stack   // offset known to runtime/cgo
    stackguard0 uintptr // offset known to liblink
    stackguard1 uintptr // offset known to liblink

    _panic         *_panic // innermost panic - offset known to liblink
    _defer         *_defer // innermost defer
    m              *m      // current m; offset known to arm liblink
    sched          gobuf
    syscallsp      uintptr        // if status==Gsyscall, syscallsp = sched.sp to use during gc
    syscallpc      uintptr        // if status==Gsyscall, syscallpc = sched.pc to use during gc
    stktopsp       uintptr        // expected sp at top of stack, to check in traceback
    param          unsafe.Pointer // passed parameter on wakeup
    atomicstatus   uint32
    stackLock      uint32 // sigprof/scang lock; TODO: fold in to atomicstatus
    goid           int64
    schedlink      guintptr
    waitsince      int64      // approx time when the g become blocked
    waitreason     waitReason // if status==Gwaiting
    preempt        bool       // preemption signal, duplicates stackguard0 = stackpreempt
    paniconfault   bool       // panic (instead of crash) on unexpected fault address
    preemptscan    bool       // preempted g does scan for gc
    gcscandone     bool       // g has scanned stack; protected by _Gscan bit in status
    gcscanvalid    bool       // false at start of gc cycle, true if G has not run since last scan; TODO: remove?
    throwsplit     bool       // must not split stack
    raceignore     int8       // ignore race detection events
    sysblocktraced bool       // StartTrace has emitted EvGoInSyscall about this goroutine
    sysexitticks   int64      // cputicks when syscall has returned (for tracing)
    traceseq       uint64     // trace event sequencer
    tracelastp     puintptr   // last P emitted an event for this goroutine
    lockedm        muintptr
    sig            uint32
    writebuf       []byte
    sigcode0       uintptr
    sigcode1       uintptr
    sigpc          uintptr
    gopc           uintptr         // pc of go statement that created this goroutine
    ancestors      *[]ancestorInfo // ancestor information goroutine(s) that created this goroutine (only used if debug.tracebackancestors)
    startpc        uintptr         // pc of goroutine function
    racectx        uintptr
    waiting        *sudog         // sudog structures this g is waiting on (that have a valid elem ptr); in lock order
    cgoCtxt        []uintptr      // cgo traceback context
    labels         unsafe.Pointer // profiler labels
    timer          *timer         // cached timer for time.Sleep
    selectDone     uint32         // are we participating in a select and did someone win the race?
    // Per-G GC state

    // gcAssistBytes is this G's GC assist credit in terms of
    // bytes allocated. If this is positive, then the G has credit
    // to allocate gcAssistBytes bytes without assisting. If this
    // is negative, then the G must correct this by performing
    // scan work. We track this in bytes to make it fast to update
    // and check for debt in the malloc hot path. The assist ratio
    // determines how this corresponds to scan work debt.
    gcAssistBytes int64
    localMap *goroutineLocalMap //这是我们添加的
}

注意不要放在第一个字段,否则编译会出现 fatal: morestack on g0

实现goroutineLocal

在 $GOROOT/src/runtime/ 目录下创建go原文件 goroutine_local.go

package runtime


type goroutineLocalMap struct {
    m map[*goroutineLocal]interface{}
}

type goroutineLocal struct {
    initfun func() interface{}
}

func NewGoroutineLocal(initfun func() interface{}) *goroutineLocal {
    return &goroutineLocal{initfun}
}

func (gl *goroutineLocal)Get() interface{} {
    if getg().localMap == nil {
        getg().localMap = &goroutineLocalMap{make(map[*goroutineLocal]interface{})}
    }
    v, ok := getg().localMap.m[gl]
    if !ok && gl.initfun != nil{
        v = gl.initfun()
    }
    return v
}

func (gl *goroutineLocal)Set(v interface{}) {
    if getg().localMap == nil {
        getg().localMap = &goroutineLocalMap{make(map[*goroutineLocal]interface{})}
    }
    getg().localMap.m[gl] = v
}

func (gl *goroutineLocal)Remove() {
    if getg().localMap != nil {
        delete(getg().localMap.m, gl)
    }
}

重新编译

cd ~/go/src
GOROOT_BOOTSTRAP='/Users/qiuxudong/go1.9' ./all.bash

写个mian函数测试一下

package main

import (
    "fmt"
    "time"
    "runtime"
)

var gl = runtime.NewGoroutineLocal(func() interface{} {
    return "default"
})

func main() {
    gl.Set("test0")
    fmt.Println(runtime.GetGoroutineId(), gl.Get())


    go func() {
        gl.Set("test1")
        fmt.Println(runtime.GetGoroutineId(), gl.Get())
        gl.Remove()
        fmt.Println(runtime.GetGoroutineId(), gl.Get())
    }()


    time.Sleep(2 * time.Second)
}

可以看到

1 test0
18 test1
18 default

同样的,这个版本也可能会内存泄露,建议主动调用Remove清除数据。但是如果goroutine销毁了,对应的数据不再被引用,是可以被GC清理的,泄露的概率降低很多。

两种实现方式GC情况对比

  1. 修改golang源代码获取goroutine id实现ThreadLocal 中的实现可以测试下泄露情况:
package goroutine_local

import (
    "testing"
    "fmt"
    "time"
    "runtime"
)

var gl = NewGoroutineLocal(func() interface{} {
    return make([]byte, 1024*1024)
})

func TestGoroutineLocal(t *testing.T) {
    var stats runtime.MemStats
    runtime.ReadMemStats(&stats)
    go func() {
        for {
            runtime.GC()
            runtime.ReadMemStats(&stats)
            fmt.Printf("HeapAlloc    = %d\n", stats.HeapAlloc)
            fmt.Printf("NumGoroutine = %d\n", runtime.NumGoroutine())
            time.Sleep(1*time.Second)
        }
    }()

    startAlloc()

    time.Sleep(10000 * time.Second)
}

func startAlloc() {
    for i := 0; i < 1000; i++ {
        runtime.GC()
        go func() {
            gl.Set(make([]byte, 10*1024*1024))
            fmt.Println(runtime.GetGoroutineId())
            //gl.Remove() //故意不删除数据,观察是否泄露
            time.Sleep(1 * time.Second) //模拟其它操作
        }()
        time.Sleep(1 * time.Second)
    }
    fmt.Println("done")
}

结果:

HeapAlloc    = 98336
NumGoroutine = 2
HeapAlloc    = 92280
NumGoroutine = 4
19
49
HeapAlloc    = 21070408
NumGoroutine = 4
5
HeapAlloc    = 31556568
NumGoroutine = 4
38
HeapAlloc    = 42043600
NumGoroutine = 4
21
HeapAlloc    = 52529512
NumGoroutine = 5
6
HeapAlloc    = 63015760
NumGoroutine = 4
7
HeapAlloc    = 73500784
NumGoroutine = 4
40
HeapAlloc    = 83986616
NumGoroutine = 4
...

可以看到是持续上升的。

  1. 本文实现的泄露情况测试代码:
package main

import (
    "fmt"
    "time"
    "runtime"
)

var gl = runtime.NewGoroutineLocal(func() interface{} {
    return make([]byte, 10*1024*1024)
})

func main() {
    var stats runtime.MemStats
    go func() {
        for {
            runtime.GC()
            runtime.ReadMemStats(&stats)
            fmt.Printf("HeapAlloc    = %d\n", stats.HeapAlloc)
            fmt.Printf("NumGoroutine = %d\n", runtime.NumGoroutine())
            time.Sleep(1*time.Second)
        }
    }()

    startAlloc()

    time.Sleep(10000 * time.Second)
}
func startAlloc() {
    for i := 0; i < 1000; i++ {
        runtime.GC()
        go func() {
            gl.Set(make([]byte, 10*1024*1024))
            fmt.Println(runtime.GetGoroutineId())
            //gl.Remove() //故意不删除数据,观察是否泄露
            time.Sleep(1 * time.Second) //模拟其它操作
        }()
        time.Sleep(1 * time.Second)
    }
    fmt.Println("done")
}

结果:

...
HeapAlloc    = 178351296
NumGoroutine = 3
114
HeapAlloc    = 178351296
NumGoroutine = 3
112
HeapAlloc    = 188837800
NumGoroutine = 3
131
HeapAlloc    = 188837800
NumGoroutine = 3
145
HeapAlloc    = 178351296
NumGoroutine = 3
146
HeapAlloc    = 178351296
NumGoroutine = 3
HeapAlloc    = 188837736
NumGoroutine = 3
132
58
HeapAlloc    = 178351296
NumGoroutine = 3
...

可以看到 HeapAlloc 不是一直上升的,中间会有GC使其下降

欢迎您扫一扫上面的二维码关注个人微信公众号
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 214,588评论 6 496
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,456评论 3 389
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 160,146评论 0 350
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,387评论 1 288
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,481评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,510评论 1 293
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,522评论 3 414
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,296评论 0 270
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,745评论 1 307
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,039评论 2 330
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,202评论 1 343
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,901评论 5 338
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,538评论 3 322
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,165评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,415评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,081评论 2 365
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,085评论 2 352

推荐阅读更多精彩内容