golang fasthttp是单线程的?

时间:2023-01-14

浏览:191

作者:佚名

本篇文章给大家分享《golang fasthttp是单线程的?》,覆盖了Golang的常见基础知识,其实一个语言的全部知识点一篇文章是不可能说完的,但希望通过这些问题,让读者对自己的掌握程度有一定的认识(B 数),从而弥补自己的不足,更好的掌握它。

问题内容

requestHandler := func(ctx *fasthttp.RequestCtx) {
        // 睡眠十秒
        time.Sleep(time.Second*time.Duration(10))
        fmt.Fprintf(ctx, "Hello, world! Requested path is %q", ctx.Path())
    }


    s := &fasthttp.Server{
    Handler: requestHandler,
    }

    if err := s.ListenAndServe("127.0.0.1:82"); err != nil {
    log.Fatalf("error in ListenAndServe: %s", err)
    }

逻辑就是睡眠10秒,开几个页面同时请求,花费的时间基本就是单线程顺序执行。。。。

正确答案

我试了以下,没什么问题,

修改了你的代码

requestHandler := func(ctx *fasthttp.RequestCtx) {
    fmt.Println("收到请求时间:", time.Now().Unix())
    // 睡眠十秒
    time.Sleep(time.Second * time.Duration(10))
    fmt.Fprintf(ctx, "Hello, world! Requested path is %q", ctx.Path())
    fmt.Println("处理完请求时间:", time.Now().Unix())
}

分别四次请求输出结果:

收到请求时间: 1500716082
收到请求时间: 1500716083
收到请求时间: 1500716084
收到请求时间: 1500716085
处理完请求时间: 1500716092
处理完请求时间: 1500716093
处理完请求时间: 1500716094
处理完请求时间: 1500716095

完全是预期的结果,是平行执行的,不存在顺序执行。

到这里,我们也就讲完了《golang fasthttp是单线程的?》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于golang的知识点!

本文内容来源于互联网,如有侵权请联系删除。

相关文章

更多

热门专题

更多
首页