标签 垃圾收集器 下的文章

Go 1.7中值得关注的几个变化

零、从Release Cycle说起

从Go 1.3版本开始,Golang核心开发Team的版本开发周期逐渐稳定下来。经过Go 1.4Go1.5Go 1.6的实践,大神Russ CoxGo wiki上大致定义了Go Release Cycle的一般流程:

  1. 半年一个major release版本。
  2. 发布流程启动时间:每年8月1日和次年2月1日(真正发布日期有可能是这个日子,也可能延后几天)。
  3. 半年的周期中,前三个月是Active Development,then 功能冻结(大约在11月1日和次年的5月1日)。接下来的三个月为test和polish。
  4. 下一个版本的启动计划时间:7月15日和1月15日,版本计划期持续15天,包括讨论这个major版本中要实现的主要功能、要fix的前期遗留的bug。
  5. release前的几个阶段版本:beta版本若干(一般是2-3个)、release candidate版本若干(一般是1-2个)和最后的release版本。
  6. major release版本的维护是通过一系列的minor版本体现的,主要是修正一些导致crash的严重问题或是安全问题,比如major release版本Go 1.6目前就有go 1.6.1和go 1.6.2两个后续minor版本发布。

在制定下一个版本启动计划时,一般会由Russ Cox在golang-dev group发起相关讨论,其他Core developer在讨论帖中谈一下自己在下一个版本中要做的事情,让所有开发者大致了解一下下个版本可能包含的功能和修复的bug概况。但这些东西是否能最终包含在下一个Release版本中,还要看Development阶段feature代码是否能完成、通过review并加入到main trunk中;如果来不及加入,这个功能可能就会放入下一个major release中,比如SSA就错过了Go 1.6(由于Go 1.5改动较大,留给Go 1.6的时间短了些)而放在了Go 1.7中了。

个人感觉Go社区采用的是一种“民主集中制”的文化,即来自Google的Golang core team的少数人具有实际话语权,尤其是几个最早加入Go team的大神,比如Rob Pike老头、Russ Cox以及Ian Lance Taylor等。当然绝大部分合理建议还是被merge到了Go代码中的,但一些与Go哲学有背离的想法,比如加入泛型、增加新类型、改善错误处理等,基本都被Rob Pike老头严词拒绝了,至少Go 1兼容版本中,大家是铁定看不到的了。至于Go 2,就连Go core team的人也不能不能打包票说一定会有这样的新语言规范。不过从Rob Pike前些阶段的一些言论中,大致可以揣摩出Pike老头正在反思Go 1的设计,也许他正在做Go 2的语言规范也说不定呢^_^。这种“文化”并不能被很多开源开发者所欣赏,在GopherChina 2016大会上,大家就对这种“有些独裁”的文化做过深刻了辩论,尤其是对比Rust那种“绝对民主”的文化。见仁见智的问题,这里就不深入了。个人觉得Go core team目前的做法还是可以很好的保持Go语言在版本上的理想的兼容性和发展的一致性的,对于一门面向工程领域的语言而言,这也许是开发者们较为看重的东西;编程语言语法在不同版本间“跳跃式”的演进也许会在短时间内带来新鲜感,但长久看来,对代码阅读和维护而言,都会有一个不小的负担。

下面回归正题。Go 1.7究竟带来了哪些值得关注的变化呢?马上揭晓^_^。(以下测试所使用的Go版本为go 1.7 beta2)。

一、语言

Go 1.7在版本计划阶段设定的目标就是改善和优化(polishing),因此在Go语言(Specification)规范方面继续保持着与Go 1兼容,因此理论上Go 1.7的发布对以往Go 1兼容的程序而言是透明的,已存在的代码均可以正常通过Go 1.7的编译并正确执行。

不过Go 1.7还是对Go1 Specs中关于“Terminating statements”的说明作了一个extremely tiny的改动:

A statement list ends in a terminating statement if the list is not empty and its final statement is terminating.
=>
A statement list ends in a terminating statement if the list is not empty and its final non-empty statement is terminating.

Specs是抽象的,例子是生动的,我们用一个例子来说明一下这个改动:

// go17-examples/language/f.go

package f

func f() int {
    return 3
    ;
}

对于f.go中f函数的body中的语句列表(statement list),所有版本的go compiler或gccgo compiler都会认为其在”return 3″这个terminating statement处terminate,即便return语句后面还有一个“;”也没关系。但Go 1.7之前的gotype工具却严格按照go 1.7之前的Go 1 specs中的说明进行校验,由于最后的statement是”;” – 一个empty statement,gotype会提示:”missing return”:

// Go 1.7前版本的gotype

$gotype f.go
f.go:6:1: missing return

于是就有了gotype与gc、gccgo行为的不一致!为此Go 1.7就做了一些specs上的改动,将statements list的terminate点从”final statement”改为“final non-empty statement”,这样即便后面再有”;”也不打紧了。于是用go 1.7中的gotype执行同样的命令,得到的结果却不一样:

// Go 1.7的gotype
$gotype f.go
没有任何错误输出

gotype默认以源码形式随着Go发布,我们需要手工将其编译为可用的工具,编译步骤如下:

$cd $GOROOT/src/go/types
$go build gotype.go
在当前目录下就会看到gotype可执行文件,你可以将其mv or cp到$GOBIN下,方便在命令行中使用。

二、Go Toolchain(工具链)

Go的toolchain的强大实用是毋容置疑的,也是让其他编程语言Fans直流口水的那部分。每次Go major version release,Go工具链都会发生或大或小的改进,这次也不例外。

1、SSA

SSA(Static Single-Assignment),对于大多数开发者来说都是不熟悉的,也是不需要关心的,只有搞编译器的人才会去认真研究它究竟为何物。对于Go语言的使用者而言,SSA意味着让编译出来的应用更小,运行得更快,未来有更多的优化空间,而这一切的获得却不需要Go开发者修改哪怕是一行代码^_^。

在Go core team最初的计划中,SSA在Go 1.6时就应该加入,但由于Go 1.6开发周期较为短暂,SSA的主要开发者Keith Randall没能按时完成相关开发,尤其是在性能问题上没能达到之前设定的目标,因此merge被推迟到了Go 1.7。即便是Go 1.7,SSA也只是先完成了x86-64系统。
据实而说,SSA后端的引入,风险还是蛮大的,因此Go在编译器中加入了一个开关”-ssa=0|1″,可以让开发者自行选择是否编译为SSA后端,默认情况下,在x86-64平台下SSA后端是打开的。同时,Go 1.7还修改了包导出的元数据的格式,由以前的文本格式换成了更为短小精炼的二进制格式,这也让Go编译出来的结果文件的Size更为small。

我们可以简单测试一下上述两个优化后对编译后结果的影响,我们以编译github.com/bigwhite/gocmpp/examples/client/例:

-rwxrwxr-x 1 share share 4278888  6月 20 14:20 client-go16*
-rwxrwxr-x 1 share share 3319205  6月 20 14:04 client-go17*
-rwxrwxr-x 1 share share 3319205  6月 20 14:05 client-go17-no-newexport*
-rwxrwxr-x 1 share share 3438317  6月 20 14:04 client-go17-no-ssa*
-rwxrwxr-x 1 share share 3438317  6月 20 14:03 client-go17-no-ssa-no-newexport*

其中:client-go17-no-ssa是通过下面命令行编译的:

$go build -a -gcflags="-ssa=0" github.com/bigwhite/gocmpp/examples/client

client-go17-no-newexport*是通过下面命令行编译的:

$go build -a -gcflags="-newexport=0" github.com/bigwhite/gocmpp/examples/client

client-go17-no-ssa-no-newexport是通过下面命令行编译的:

$go build -a -gcflags="-newexport=0 -ssa=0" github.com/bigwhite/gocmpp/examples/client

对比client-go16和client-go17,我们可以看到默认情况下Go 17编译出来的可执行程序(client-go17)比Go 1.6编译出来的程序(client-go16)小了约21%,效果十分明显。这也与Go官方宣称的file size缩小20%~30%de 平均效果相符。

不过对比client-go17和client-go17-no-newexport,我们发现,似乎-newexport=0并没有起到什么作用,两个最终可执行文件的size相同。这个在ubuntu 14.04以及darwin平台上测试的结果均是如此,暂无解。

引入SSA后,官方说法是:程序的运行性能平均会提升5%~35%,数据来源于官方的benchmark数据,这里就不再重复测试了。

2、编译器编译性能

Go 1.5发布以来,Go的编译器性能大幅下降就遭到的Go Fans们的“诟病”,虽然Go Compiler的性能与其他编程语言横向相比依旧是“独领风骚”。最差时,Go 1.5的编译构建时间是Go 1.4.x版本的4倍还多。这个问题也引起了Golang老大Rob Pike的极大关注,在Russ Cox筹划Go 1.7时,Rob Pike就极力要求要对Go compiler&linker的性能进行优化,于是就有了Go 1.7“全民优化”Go编译器和linker的上百次commit,至少从目前来看,效果是明显的。

Go大神Dave Cheney为了跟踪开发中的Go 1.7的编译器性能情况,建立了三个benchmark:benchjujubenchkubebenchgogs。Dave上个月最新贴出的一幅性能对比图显示:编译同一项目,Go 1.7编译器所需时间仅约是Go 1.6的一半,Go 1.4.3版本的2倍;也就是说经过优化后,Go 1.7的编译性能照比Go 1.6提升了一倍,离Go 1.4.3还有一倍的差距。

img{}

3、StackFrame Pointer

在Go 1.7功能freeze前夕,Russ Cox将StackFrame Pointer加入到Go 1.7中了,目的是使得像Linux Perf或Intel Vtune等工具能更高效的抓取到go程序栈的跟踪信息。但引入STackFrame Pointer会有一些性能上的消耗,大约在2%左右。通过下面环境变量设置可以关闭该功能:

export GOEXPERIMENT=noframepointer

4、Cgo增加C.CBytes

Cgo的helper函数在逐渐丰富,这次Cgo增加C.CBytes helper function就是源于开发者的需求。这里不再赘述Cgo的这些Helper function如何使用了,通过一小段代码感性了解一下即可:

// go17-examples/gotoolchain/cgo/print.go

package main

// #include <stdio.h>
// #include <stdlib.h>
//
// void print(void *array, int len) {
//  char *c = (char*)array;
//
//  for (int i = 0; i < len; i++) {
//      printf("%c", *(c+i));
//  }
//  printf("\n");
// }
import "C"

import "unsafe"

func main() {
    var s = "hello cgo"
    csl := C.CBytes([]byte(s))
    C.print(csl, C.int(len(s)))
    C.free(unsafe.Pointer(csl))
}

执行该程序:

$go run print.go
hello cgo

5、其他小改动

  • 经过Go 1.5和Go 1.6实验的go vendor机制在Go 1.7中将正式去掉GO15VENDOREXPERIMENT环境变量开关,将vendor作为默认机制。
  • go get支持git.openstack.org导入路径。
  • go tool dist list命令将打印所有go支持的系统和硬件架构,在我的机器上输出结果如下:
$go tool dist list
android/386
android/amd64
android/arm
android/arm64
darwin/386
darwin/amd64
darwin/arm
darwin/arm64
dragonfly/amd64
freebsd/386
freebsd/amd64
freebsd/arm
linux/386
linux/amd64
linux/arm
linux/arm64
linux/mips64
linux/mips64le
linux/ppc64
linux/ppc64le
linux/s390x
nacl/386
nacl/amd64p32
nacl/arm
netbsd/386
netbsd/amd64
netbsd/arm
openbsd/386
openbsd/amd64
openbsd/arm
plan9/386
plan9/amd64
plan9/arm
solaris/amd64
windows/386
windows/amd64

三、标准库

1、支持subtests和sub-benchmarks

表驱动测试是golang内置testing框架的一个最佳实践,基于表驱动测试的思路,Go 1.7又进一步完善了testing的组织体系,增加了subtests和sub-benchmarks。目的是为了实现以下几个Features:

  • 通过外部command line(go test –run=xx)可以从一个table中选择某个test或benchmark,用于调试等目的;
  • 简化编写一组相似的benchmarks;
  • 在subtest中使用Fail系列方法(如FailNow,SkipNow等);
  • 基于外部或动态表创建subtests;
  • 更细粒度的setup和teardown控制,而不仅仅是TestMain提供的;
  • 更多的并行控制;
  • 与顶层函数相比,对于test和benchmark来说,subtests和sub-benchmark代码更clean。

下面是一个基于subtests文档中demo改编的例子:

传统的Go 表驱动测试就像下面代码中TestSumInOldWay一样:

// go17-examples/stdlib/subtest/foo_test.go

package foo

import (
    "fmt"
    "testing"
)

var tests = []struct {
    A, B int
    Sum  int
}{
    {1, 2, 3},
    {1, 1, 2},
    {2, 1, 3},
}

func TestSumInOldWay(t *testing.T) {
    for _, tc := range tests {
        if got := tc.A + tc.B; got != tc.Sum {
            t.Errorf("%d + %d = %d; want %d", tc.A, tc.B, got, tc.Sum)
        }
    }
}

对于这种传统的表驱动测试,我们在控制粒度上仅能在顶层测试方法层面,即TestSumInOldWay这个层面:

$go test --run=TestSumInOldWay
PASS
ok      github.com/bigwhite/experiments/go17-examples/stdlib/subtest    0.008s

同时为了在case fail时更容易辨别到底是哪组数据导致的问题,Errorf输出时要带上一些测试数据的信息,比如上面代码中的:”%d+%d=%d; want %d”。

若通过subtests来实现,我们可以将控制粒度细化到subtest层面。并且由于subtest自身具有subtest name唯一性,无需在Error中带上那组测试数据的信息:

// go17-examples/stdlib/subtest/foo_test.go

func assertEqual(A, B, expect int, t *testing.T) {
    if got := A + B; got != expect {
        t.Errorf("got %d; want %d", got, expect)
    }
}

func TestSumSubTest(t *testing.T) {
    //setup code ... ...

    for i, tc := range tests {
        t.Run("A=1", func(t *testing.T) {
            if tc.A != 1 {
                t.Skip(i)
            }
            assertEqual(tc.A, tc.B, tc.Sum, t)
        })

        t.Run("A=2", func(t *testing.T) {
            if tc.A != 2 {
                t.Skip(i)
            }
            assertEqual(tc.A, tc.B, tc.Sum, t)
        })
    }

    //teardown code ... ...
}

我们故意将tests数组中的第三组测试数据的Sum值修改错误,这样便于对比测试结果:

var tests = []struct {
    A, B int
    Sum  int
}{
    {1, 2, 3},
    {1, 1, 2},
    {2, 1, 4},
}

执行TestSumSubTest:

$go test --run=TestSumSubTest
--- FAIL: TestSumSubTest (0.00s)
    --- FAIL: TestSumSubTest/A=2#02 (0.00s)
        foo_test.go:19: got 3; want 4
FAIL
exit status 1
FAIL    github.com/bigwhite/experiments/go17-examples/stdlib/subtest    0.007s

分别执行”A=1″和”A=2″的两个subtest:

$go test --run=TestSumSubTest/A=1
PASS
ok      github.com/bigwhite/experiments/go17-examples/stdlib/subtest    0.007s

$go test --run=TestSumSubTest/A=2
--- FAIL: TestSumSubTest (0.00s)
    --- FAIL: TestSumSubTest/A=2#02 (0.00s)
        foo_test.go:19: got 3; want 4
FAIL
exit status 1
FAIL    github.com/bigwhite/experiments/go17-examples/stdlib/subtest    0.007s

测试的结果验证了前面说到的两点:
1、subtest的输出自带唯一标识,比如:“FAIL: TestSumSubTest/A=2#02 (0.00s)”
2、我们可以将控制粒度细化到subtest的层面。

从代码的形态上来看,subtest支持对测试数据进行分组编排,比如上面的测试就将TestSum分为A=1和A=2两组,以便于分别单独控制和结果对比。

另外由于控制粒度支持subtest层,setup和teardown也不再局限尽在TestMain级别了,开发者可以在每个top-level test function中,为其中的subtest加入setup和teardown,大体模式如下:

func TestFoo(t *testing.T) {
    //setup code ... ...

    //subtests... ...

    //teardown code ... ...
}

Go 1.7中的subtest同样支持并发执行:

func TestSumSubTestInParalell(t *testing.T) {
    t.Run("blockgroup", func(t *testing.T) {
        for _, tc := range tests {
            tc := tc
            t.Run(fmt.Sprint(tc.A, "+", tc.B), func(t *testing.T) {
                t.Parallel()
                assertEqual(tc.A, tc.B, tc.Sum, t)
            })
        }
    })
    //teardown code
}

这里嵌套了两层Subtest,”blockgroup”子测试里面的三个子测试是相互并行(Paralell)执行,直到这三个子测试执行完毕,blockgroup子测试的Run才会返回。而TestSumSubTestInParalell与foo_test.go中的其他并行测试function(如果有的话)的执行是顺序的。

sub-benchmark在形式和用法上与subtest类似,这里不赘述了。

2、Context包

Go 1.7将原来的golang.org/x/net/context包挪入了标准库中,放在$GOROOT/src/context下面,这显然是由于context模式用途广泛,Go core team响应了社区的声音,同时这也是Go core team自身的需要。Std lib中net、net/http、os/exec都用到了context。关于Context的详细说明,没有哪个比Go team的一篇”Go Concurrent Patterns:Context“更好了。

四、其他改动

Runtime这块普通开发者很少使用,一般都是Go core team才会用到。值得注意的是Go 1.7增加了一个runtime.Error(接口),所有runtime引起的panic,其panic value既实现了标准error接口,也实现了runtime.Error接口。

Golang的GC在1.7版本中继续由Austin Clements和Rick Hudson进行打磨和优化。

Go 1.7编译的程序的执行效率由于SSA的引入和GC的优化,整体上会平均提升5%-35%(在x86-64平台上)。一些标准库的包得到了显著的优化,比如:crypto/sha1, crypto/sha256, encoding/binary, fmt, hash/adler32, hash/crc32, hash/crc64, image/color, math/big, strconv, strings, unicode, 和unicode/utf16,性能提升在10%以上。

Go 1.7还增加了对使用二进制包(非源码)构建程序的实验性支持(出于一些对商业软件发布形态的考虑),但Go core team显然是不情愿在这方面走太远,不承诺对此进行完整的工具链支持。

标准库中其他的一些细微改动,大家尽可以参考Go 1.7 release notes。

本文涉及到的example代码在这里可以下载到。

Go 1.6中值得关注的几个变化

北京时间2016年2月18日凌晨,在Go 1.5发布 半年后,Go 1.6正式Release 了。与Go 1.5的“惊天巨变”(主要指Go自举)相比,Go 1.6的Change 算是很小的了,当然这也与Go 1.6的dev cycle过于短暂有关。但Go社区对此次发布却甚是重视,其热烈程度甚至超出了Go 1.5。在Dave Cheney的倡导 下,Gophers们在全球各地举行了Go 1.6 Release Party。 Go Core Team也在Reddit上开了一个AMA – Ask Me Anything,RobPike、Russ Cox(Rsc)、Bradfitz等Go大神齐上阵,对广大Gophers们在24hour内的问题有问必答。

言归正传,我们来看看Go 1.6中哪些变化值得我们关注。不过在说变化之前,我们先提一嘴Go 1.6没变的,那就是Go语言的language specification,依旧保持Go 1兼容不变。预计在未来的几个stable release版本中,我们也不会看到Go language specification有任何改动。

一、cgo

cgo的变化在于:
1、定义了在Go code和C code间传递Pointer,即C code与Go garbage collector共存的rules和restriction;
2、在runtime加入了对违规传递的检查,检查的开关和力度由GODEBUG=cgocheck=1[0,2]控制。1是默认;0是关闭检 查;2是更全面彻底但代价更高的检查。

这个Proposal是由Ian Lance Taylor提出的。大致分为两种情况:

(一) Go调用C Code时

Go调用C Code时,Go传递给C Code的Go Pointer所指的Go Memory中不能包含任何指向Go Memory的Pointer。我们分为几种情况来探讨一下:

1、传递一个指向Struct的指针

//cgo1_struct.go
package main

/*
#include <stdio.h>
struct Foo{
    int a;
    int *p;
};

void plusOne(struct Foo *f) {
    (f->a)++;
    *(f->p)++;
}
*/
import "C"
import "unsafe"
import "fmt"

func main() {
    f := &C.struct_Foo{}
    f.a = 5
    f.p = (*C.int)((unsafe.Pointer)(new(int)))
    //f.p = &f.a

    C.plusOne(f)
    fmt.Println(int(f.a))
}

从cgo1_struct.go代码中可以看到,Go code向C code传递了一个指向Go Memory(Go分配的)指针f,但f指向的Go Memory中有一个指针p指向了另外一处Go Memory: new(int),我们来run一下这段代码:

$go run cgo1_struct.go
# command-line-arguments
./cgo1_struct.go:12:2: warning: expression result unused [-Wunused-value]
panic: runtime error: cgo argument has Go pointer to Go pointer

goroutine 1 [running]:
panic(0x4068400, 0xc82000a110)
    /Users/tony/.bin/go16/src/runtime/panic.go:464 +0x3e6
main.main()
    /Users/tony/test/go/go16/cgo/cgo1_struct.go:24 +0xb9
exit status 2

代码出现了Panic,并提示:“cgo argument has Go pointer to Go pointer”。我们的代码违背了Cgo Pointer传递规则,即便让f.p指向struct自身内存也是不行的,比如f.p = &f.a。

2、传递一个指向struct field的指针

按照rules中的说明,如果传递的是一个指向struct field的指针,那么”Go Memory”专指这个field所占用的内存,即便struct中有其他field指向其他Go memory也不打紧:

//cgo1_structfield.go
package main

/*
#include <stdio.h>
struct Foo{
    int a;
    int *p;
};

void plusOne(int *i) {
    (*i)++;
}
*/
import "C"
import (
    "fmt"
    "unsafe"
)

func main() {
    f := &C.struct_Foo{}
    f.a = 5
    f.p = (*C.int)((unsafe.Pointer)(new(int)))

    C.plusOne(&f.a)
    fmt.Println(int(f.a))
}

上述程序的运行结果:

$go run cgo1_structfield.go
6

3、传递一个指向slice or array中的element的指针

和传递struct field不同,传递一个指向slice or array中的element的指针时,需要考虑的Go Memory的范围不仅仅是这个element,而是整个Array或整个slice背后的underlying array所占用的内存区域,要保证这个区域内不包含指向任意Go Memory的指针。我们来看代码示例:

//cgo1_sliceelem.go
package main

/*
#include <stdio.h>
void plusOne(int **i) {
    (**i)++;
}
*/
import "C"
import (
    "fmt"
    "unsafe"
)

func main() {
    sl := make([]*int, 5)
    var a int = 5
    sl[1] = &a
    C.plusOne((**C.int)((unsafe.Pointer)(&sl[0])))
    fmt.Println(sl[0])
}

从这个代码中,我们看到我们传递的是slice的第一个element的地址,即&sl[0]。我们并未给sl[0]赋值,但sl[1] 被赋值为另外一块go memory的address(&a),当我们将&sl[0]传递给plusOne时,执行结果如下:

$go run cgo1_sliceelem.go
panic: runtime error: cgo argument has Go pointer to Go pointer

goroutine 1 [running]:
panic(0x40dbac0, 0xc8200621d0)
    /Users/tony/.bin/go16/src/runtime/panic.go:464 +0x3e6
main.main()
    /Users/tony/test/go/go16/cgo/cgo1_sliceelem.go:19 +0xe4
exit status 2

由于违背规则,因此runtime panic了。

(二) C调用Go Code时

1、C调用的Go函数不能返回指向Go分配的内存的指针

我们看下面例子:

//cgo2_1.go

package main

// extern int* goAdd(int, int);
//
// static int cAdd(int a, int b) {
//     int *i = goAdd(a, b);
//     return *i;
// }
import "C"
import "fmt"

//export goAdd
func goAdd(a, b C.int) *C.int {
    c := a + b
    return &c
}

func main() {
    var a, b int = 5, 6
    i := C.cAdd(C.int(a), C.int(b))
    fmt.Println(int(i))
}

可以看到:goAdd这个Go函数返回了一个指向Go分配的内存(&c)的指针。运行上述代码,结果如下:

$go run cgo2_1.go
panic: runtime error: cgo result has Go pointer

goroutine 1 [running]:
panic(0x40dba40, 0xc82006e1c0)
    /Users/tony/.bin/go16/src/runtime/panic.go:464 +0x3e6
main._cgoexpwrap_872b2f2e7532_goAdd.func1(0xc820049d98)
    command-line-arguments/_obj/_cgo_gotypes.go:64 +0x3a
main._cgoexpwrap_872b2f2e7532_goAdd(0x600000005, 0xc82006e19c)
    command-line-arguments/_obj/_cgo_gotypes.go:66 +0x89
main._Cfunc_cAdd(0x600000005, 0x0)
    command-line-arguments/_obj/_cgo_gotypes.go:45 +0x41
main.main()
    /Users/tony/test/go/go16/cgo/cgo2_1.go:20 +0x35
exit status 2

2、Go code不能在C分配的内存中存储指向Go分配的内存的指针

下面的例子模拟了这一情况:

//cgo2_2.go
package main

// #include <stdlib.h>
// extern void goFoo(int**);
//
// static void cFoo() {
//     int **p = malloc(sizeof(int*));
//     goFoo(p);
// }
import "C"

//export goFoo
func goFoo(p **C.int) {
    *p = new(C.int)
}

func main() {
    C.cFoo()
}

不过针对此例,默认的GODEBUG=cgocheck=1偏是无法check出问题。我们将GODEBUG=cgocheck改为=2试试:

$GODEBUG=cgocheck=2 go run cgo2_2.go
write of Go pointer 0xc82000a0f8 to non-Go memory 0x4300000
fatal error: Go pointer stored into non-Go memory

runtime stack:
runtime.throw(0x4089800, 0x24)
    /Users/tony/.bin/go16/src/runtime/panic.go:530 +0x90
runtime.cgoCheckWriteBarrier.func1()
    /Users/tony/.bin/go16/src/runtime/cgocheck.go:44 +0xae
runtime.systemstack(0x7fff5fbff8c0)
    /Users/tony/.bin/go16/src/runtime/asm_amd64.s:291 +0x79
runtime.mstart()
    /Users/tony/.bin/go16/src/runtime/proc.go:1048
... ...
goroutine 17 [syscall, locked to thread]:
runtime.goexit()
    /Users/tony/.bin/go16/src/runtime/asm_amd64.s:1998 +0x1
exit status 2

果真runtime panic: write of Go pointer 0xc82000a0f8 to non-Go memory 0×4300000

二、HTTP/2

HTTP/2原本是bradfitz维护的x项目,之前位于golang.org/x/net/http2包中,Go 1.6无缝合入Go标准库net/http包中。并且当你你使用https时,client和server端将自动默认使用HTTP/2协议。

HTTP/2与HTTP1.x协议不同在于其为二进制协议,而非文本协议,性能自是大幅提升。HTTP/2标准已经发布,想必未来若干年将大行其道。

HTTP/2较为复杂,这里不赘述,后续maybe会单独写一篇GO和http2的文章说明。

三、Templates

由于不开发web,templates我日常用的很少。这里粗浅说说templates增加的两个Feature

trim空白字符

Go templates的空白字符包括:空格、水平tab、回车和换行符。在日常编辑模板时,这些空白尤其难于处理,由于是对beatiful format和code readabliity有“强迫症”的同学,更是在这方面话费了不少时间。

Go 1.6提供了{{-和-}}来帮助大家去除action前后的空白字符。下面的例子很好的说明了这一点:

//trimwhitespace.go
package main

import (
    "log"
    "os"
    "text/template"
)

var items = []string{"one", "two", "three"}

func tmplbefore15() {
    var t = template.Must(template.New("tmpl").Parse(`
    <ul>
    {{range . }}
        <li>{{.}}</li>
    {{end }}
    </ul>
    `))

    err := t.Execute(os.Stdout, items)
    if err != nil {
        log.Println("executing template:", err)
    }
}

func tmplaftergo16() {
    var t = template.Must(template.New("tmpl").Parse(`
    <ul>
    {{range . -}}
        <li>{{.}}</li>
    {{end -}}
    </ul>
    `))

    err := t.Execute(os.Stdout, items)
    if err != nil {
        log.Println("executing template:", err)
    }
}

func main() {
    tmplbefore15()
    tmplaftergo16()
}

这个例子的运行结果:

$go run trimwhitespace.go

    <ul>

        <li>one</li>

        <li>two</li>

        <li>three</li>

    </ul>

    <ul>
    <li>one</li>
    <li>two</li>
    <li>three</li>
    </ul>

block action

block action提供了一种在运行时override已有模板形式的能力。

package main

import (
    "log"
    "os"
    "text/template"
)

var items = []string{"one", "two", "three"}

var overrideItemList = `
{{define "list" -}}
    <ul>
    {{range . -}}
        <li>{{.}}</li>
    {{end -}}
    </ul>
{{end}}
`

var tmpl = `
    Items:
    {{block "list" . -}}
    <ul>
    {{range . }}
        <li>{{.}}</li>
    {{end }}
    </ul>
    {{end}}
`

var t *template.Template

func init() {
    t = template.Must(template.New("tmpl").Parse(tmpl))
}

func tmplBeforeOverride() {
    err := t.Execute(os.Stdout, items)
    if err != nil {
        log.Println("executing template:", err)
    }
}

func tmplafterOverride() {
    t = template.Must(t.Parse(overrideItemList))
    err := t.Execute(os.Stdout, items)
    if err != nil {
        log.Println("executing template:", err)
    }
}

func main() {
    fmt.Println("before override:")
    tmplBeforeOverride()
    fmt.Println("after override:")
    tmplafterOverride()
}

原模板tmpl中通过block action定义了一处名为list的内嵌模板锚点以及初始定义。后期运行时通过re-parse overrideItemList达到修改模板展示形式的目的。

上述代码输出结果:

$go run blockaction.go
before override:

    Items:
    <ul>

        <li>one</li>

        <li>two</li>

        <li>three</li>

    </ul>

after override:

    Items:
    <ul>
    <li>one</li>
    <li>two</li>
    <li>three</li>
    </ul>

四、Runtime

降低大内存使用时的GC latency

Go 1.5.x用降低一些吞吐量的代价换取了10ms以下的GC latency。不过针对Go 1.5,官方给出的benchmark图中,内存heap size最多20G左右。一旦超过20G,latency将超过10ms,也许会线性增长。
在Go 1.6中,官方给出的benchmark图中当内存heap size在200G时,GC latency依旧可以稳定在10ms;在heap size在20G以下时,latency降到了6ms甚至更小。

panic info

Go 1.6之前版本,一旦程序以panic方式退出,runtime便会将所有goroutine的stack信息打印出来:

$go version
go version go1.5.2 darwin/amd64
[ ~/test/go/go16/runtime]$go run panic.go
panic: runtime error: invalid memory address or nil pointer dereference
[signal 0xb code=0x1 addr=0x0 pc=0x20d5]

goroutine 1 [running]:
main.main()
    /Users/tony/test/go/go16/runtime/panic.go:19 +0x95

goroutine 4 [select (no cases)]:
main.main.func1(0x8200f40f0)
    /Users/tony/test/go/go16/runtime/panic.go:13 +0x26
created by main.main
    /Users/tony/test/go/go16/runtime/panic.go:14 +0x72
... ...

而Go 1.6后,Go只会打印正在running的goroutine的stack信息,因此它才是最有可能造成panic的真正元凶:

go 1.6:
$go run panic.go
panic: runtime error: invalid memory address or nil pointer dereference
[signal 0xb code=0x1 addr=0x0 pc=0x20d5]

goroutine 1 [running]:
panic(0x61e80, 0x8200ee0c0)
    /Users/tony/.bin/go16/src/runtime/panic.go:464 +0x3e6
main.main()
    /Users/tony/test/go/go16/runtime/panic.go:19 +0x95
exit status 2

map race detect

Go原生的map类型是goroutine-unsafe的,长久以来,这给很多Gophers带来了烦恼。这次Go 1.6中Runtime增加了对并发访问map的检测以降低gopher们使用map时的心智负担。

这里借用了Francesc Campoy在最近一期”The State of Go”中的示例程序:

package main

import "sync"

func main() {
    const workers = 100

    var wg sync.WaitGroup
    wg.Add(workers)
    m := map[int]int{}
    for i := 1; i <= workers; i++ {
        go func(i int) {
            for j := 0; j < i; j++ {
                m[i]++
            }
            wg.Done()
        }(i)
    }
    wg.Wait()
}

执行结果:

$ go run map.go
fatal error: concurrent map writes
fatal error: concurrent map writes
... ...

这里在双核i5 mac air下亲测时,发现当workers=2,3,4均不能检测出race。当workers >= 5时可以检测到。

五、其他

手写parser替代yacc生成的parser

这个变化对Gopher们是透明的,但对于Go compiler本身却是十分重要的。

Robert Riesemer在Go 1.6代码Freezing前commit了手写Parser,以替代yacc生成的parser。在AMA上RobPike给出了更换Parser的些许理由:
1、Go compiler可以少维护一个yacc工具,这样更加cleaner;
2、手写Parser在性能上可以快那么一点点。

Go 1.6中GO15VENDOREXPERIMENT将默认开启

根据当初在Go 1.5中引入vendor时的计划,Go 1.6中GO15VENDOREXPERIMENT将默认开启。这显然会导致一些不兼容的情况出现:即如果你的代码在之前并未使用vendor机制,但目录组织中有vendor目录。Go Core team给出的解决方法就是删除vendor目录或改名。

遗留问题是否解决

Go 1.5发布后,曾经发现两个问题,直到Go 1.5.3版本发布也未曾解决,那么Go 1.6是否解决了呢?我们来验证一下。

internal问题

该问题的具体细节可参看我在go github上提交的issue 12217,我在自己的experiments中提交了问题的验证环境代码,这次我们使用Go 1.6看看internal问题是否还存在:

$cd $GOPATH/src/github.com/bigwhite/experiments/go15-internal-issue-12217
$cd otherpkg/
$go build main.go
package main
    imports github.com/bigwhite/experiments/go15-internal-issue-12217/mypkg/internal/foo: use of internal package not allowed

这回go compiler给出了error,而不是像之前版本那样顺利编译通过。看来这个问题是fix掉了。

GOPATH之外vendor机制是否起作用的问题

我们先建立实验环境:

$tree
.
└── testvendor
    └── src
        └── proj1
            ├── main.go
            └── vendor
                └── github.com
                    └── bigwhite
                        └── foo
                            └── foolib.go

进入proj1,build main.go

go build main.go
main.go:3:8: cannot find package "github.com/bigwhite/foo" in any of:
    /Users/tony/.bin/go16/src/github.com/bigwhite/foo (from $GOROOT)
    /Users/tony/Test/GoToolsProjects/src/github.com/bigwhite/foo (from $GOPATH)

go 1.6编译器没有关注同路径下的vendor目录,build失败。

我们设置GOPATH=xxx/testvendor后,再来build:

$export GOPATH=~/Test/go/go16/others/testvendor
$go run main.go
Hello from temp vendor

这回编译运行ok。

由此看来,Go 1.6 vendor在GOPATH外依旧不生效。

六、小结

Go 1.6标准库细微变化还是有很多的,在Go 1.6 Release Notes中可细细品味。

Go 1.6的编译速度、编译出的程序的运行性能与Go 1.5.x也大致无二异。

另外本文实现环境如下:

go version go1.6 darwin/amd64
Darwin tonydeair-2.lan 13.1.0 Darwin Kernel Version 13.1.0: Thu Jan 16 19:40:37 PST 2014; root:xnu-2422.90.20~2/RELEASE_X86_64 x86_64

实验代码可在这里下载。

如发现本站页面被黑,比如:挂载广告、挖矿等恶意代码,请朋友们及时联系我。十分感谢! Go语言第一课 Go语言精进之路1 Go语言精进之路2 商务合作请联系bigwhite.cn AT aliyun.com

欢迎使用邮件订阅我的博客

输入邮箱订阅本站,只要有新文章发布,就会第一时间发送邮件通知你哦!

这里是 Tony Bai的个人Blog,欢迎访问、订阅和留言! 订阅Feed请点击上面图片

如果您觉得这里的文章对您有帮助,请扫描上方二维码进行捐赠 ,加油后的Tony Bai将会为您呈现更多精彩的文章,谢谢!

如果您希望通过微信捐赠,请用微信客户端扫描下方赞赏码:

如果您希望通过比特币或以太币捐赠,可以扫描下方二维码:

比特币:

以太币:

如果您喜欢通过微信浏览本站内容,可以扫描下方二维码,订阅本站官方微信订阅号“iamtonybai”;点击二维码,可直达本人官方微博主页^_^:
本站Powered by Digital Ocean VPS。
选择Digital Ocean VPS主机,即可获得10美元现金充值,可 免费使用两个月哟! 著名主机提供商Linode 10$优惠码:linode10,在 这里注册即可免费获 得。阿里云推荐码: 1WFZ0V立享9折!


View Tony Bai's profile on LinkedIn
DigitalOcean Referral Badge

文章

评论

  • 正在加载...

分类

标签

归档



View My Stats