线上一个服务有个严重问题,处理消息数1k/s提升不上去,经过查看是阻塞在了一个新加的函数上,这个函数负责收集信息,送到一个channel上,再由某个函数处理,这个处理函数很简单,看不出任何问题,最大的特点是为了不加锁,只起一个goroutine。

结论很明显了,只起一个goroutine,当系统繁忙和存在大量goroutine的时候,会得不到调度,导致收集函数阻塞,进而导致消息处理数上不去。

该获得调度的没有被调度,不该获得调度的却获得调度了,而go runtime不可能知道那个goroutine应该被调度,只能是公平调度,但是公平调度反而造成了堵塞!

这种问题其实很普遍,不是一个goroutine的问题!就算你开了多个goroutine,仍然可能得不到调度!比如说redis pool,开了20多个goroutine,仍然可能发生阻塞!

这篇文章《记一次latency问题排查:谈Go的公平调度的缺陷》也谈到go这个问题,作者认为问题无解。

其实我们可以试试,golang提供的一个更简单的方法,runtime.LockOSThread()。
LockOSThread wires the calling goroutine to its current operating system thread. Until the calling goroutine exits or calls UnlockOSThread, it will always execute in that thread, and no other goroutine can.

下面的test,显示了runtime.LockOSThread()的确能影响调度,注释掉runtime.LockOSThread(),有2-60倍的时间差。

 

package main

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

func main() {

	var ch = make(chan bool, 20000)
	var begin = make(chan bool)

	go func() {
		runtime.LockOSThread()
		<-begin
		fmt.Println("begin")
		tm := time.Now()
		for i := 0; i < 10000000; i++ {
			<-ch
		}
		fmt.Println(time.Now().Sub(tm))
		os.Exit(0)
	}()

	for i := 0; i < 50000; i++ {
		// 负载
		go func() {
			var count int
			load := 100000
			for {
				count++
				if count%load == 2 {
					runtime.Gosched()
				}
			}
		}()
	}

	for i := 0; i < 20; i++ {
		go func() {
			for {
				ch <- true
			}
		}()
	}

	fmt.Println("all start")
	begin <- true

	select {}
}

 

 

版权声明:本文为dearplain原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/dearplain/p/8276138.html