登录
首页 >  Golang >  Go问答

为什么使用 WaitGroup 时单个 goroutine 在上传文件过程中会发生死锁?

来源:stackoverflow

时间:2024-02-06 16:54:24 335浏览 收藏

大家好,今天本人给大家带来文章《为什么使用 WaitGroup 时单个 goroutine 在上传文件过程中会发生死锁?》,文中内容主要涉及到,如果你对Golang方面的知识点感兴趣,那就请各位朋友继续看下去吧~希望能真正帮到你们,谢谢!

问题内容

编辑:主要问题是实际的上传过程,而不是发生的死锁,这只是由错误放置的 wg.wait() 引起的

我正在尝试通过 api 将文件上传到在线文件托管服务 (https://anonfiles.com/)。上传文件大小限制为 20gb。

我可以使用下面的代码上传一个大约 2kb 的简单文本文件。但是,如果我尝试对较大的文件(例如大约 2mb)执行相同的操作,我会从他们的 api 中收到以下错误:no file selected

我认为这是因为代码(下面)没有等待 go 例程正确完成,所以我添加了一个等待组。然后我从 go 中得到了这个错误:fatal error: all goroutine are sleep - deadlock!

我尝试删除下面的 waitgroup,似乎导致了死锁;但是 go 例程下面的代码将在 go 例程实际完成之前运行。

删除 waitgroup 后,我仍然可以上传 kb 大小的文件,但较大的文件无法正确上传到文件托管,因为我从其 api 收到 no file selected 错误。

package main

import (
    "fmt"
    "io"
    "log"
    "math/rand"
    "mime/multipart"
    "net/http"
    "os"
    "sync"
    "time"
)

func main() {
    client := http.Client{}

    // Upload a >2MB wallpaper.
    file, err := os.Open("./wallpaper.jpg")
    if err != nil {
        log.Fatal(err)
    }

    defer file.Close()

    reader, writer := io.Pipe()
    multipart := multipart.NewWriter(writer)

    /* 
    Added Waitgroup to make sure the routine properly finishes. Instead, causes deadlock.
    wg := new(sync.WaitGroup)
    wg.Add(1) 
    */

    go func() {
        fmt.Println("Starting Upload...")
        defer wg.Done()
        defer writer.Close()
        defer multipart.Close()

        part, err := multipart.CreateFormFile("file", file.Name())
        if err != nil {
            log.Fatal(err)
        }

        fmt.Println("Copying...")
        if _, err = io.Copy(part, file); err != nil {
            log.Fatal(err)
        }
    }()

    fmt.Println("The code below will run before the goroutine is finished; without the WaitGroup.")

    req, err := http.NewRequest(http.MethodPost, "https://api.anonfiles.com/upload", reader)
    if err != nil {
        log.Fatal(err)
    }

    req.Header.Add("Content-Type", multipart.FormDataContentType())

    resp, err := client.Do(req)
    if err != nil {
        log.Fatal(err)
    }

    wg.Wait()

    defer resp.Body.Close()

    body, err := io.ReadAll(resp.Body)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(string(body))
}

我研究了几个问题,但似乎没有一个问题适用于我的问题。是什么原因导致这个锁定?可以采取哪些不同的做法?也许这是一些菜鸟错误,任何建议或帮助将不胜感激。


正确答案


tl;dr

设置请求的 content-length 标头。

本答案末尾附有一个工作演示。

调试

我认为死锁问题在这里并不重要。你的目的是上传文件到https://anonfiles.com/,所以我会重点调试上传问题。

首先,让我们使用 curl 上传文件:

curl -f "[email protected]" https://api.anonfiles.com/upload

它有效。

然后让我们上传与您的演示相同的文件,它失败并出现误导性响应:

{
  "status": false,
  "error": {
    "message": "no file chosen.",
    "type": "error_file_not_provided",
    "code": 10
  }
}

现在让我们将目标 https://api.anonfiles.com/upload 替换为 https://httpbin.org/post,以便我们可以比较请求:

{
   "args": {}, 
   "data": "", 
   "files": {
     "file": "aaaaaaaaaa\n"
   }, 
   "form": {}, 
   "headers": {
-    "accept": "*/*", 
-    "content-length": "197", 
-    "content-type": "multipart/form-data; boundary=------------------------bd4a81e725230fa6", 
+    "accept-encoding": "gzip",
+    "content-type": "multipart/form-data; boundary=2d4e7969789ed6ef6ff3e7b815db3aa040fd3994a34fbaedec85240dc5af",
     "host": "httpbin.org", 
-    "user-agent": "curl/7.81.0", 
-    "x-amzn-trace-id": "root=1-63747739-2c1dab1b122b7e3a4db8ca79"
+    "transfer-encoding": "chunked",
+    "user-agent": "go-http-client/2.0",
+    "x-amzn-trace-id": "root=1-63747872-2fbc85f81c6dde7e5b2091c4"
   }, 
   "json": null, 
   "origin": "47.242.15.156", 
   "url": "https://httpbin.org/post"
 }

显着的区别是 curl 发送 "content-length": "197" 而 go 应用发送 "transfer-encoding": "chunked"

让我们尝试修改 go 应用以发送 content-length 标头:

package main

import (
    "bytes"
    "fmt"
    "io"
    "log"
    "mime/multipart"
    "net/http"
    "strings"
)

func main() {
    source := strings.NewReader(strings.Repeat("a", 1<<21))

    buf := new(bytes.Buffer)
    multipart := multipart.NewWriter(buf)

    part, err := multipart.CreateFormFile("file", "test.txt")
    if err != nil {
        log.Fatal(err)
    }

    if _, err := io.Copy(part, source); err != nil {
        log.Fatal(err)
    }
    multipart.Close()

    req, err := http.NewRequest(http.MethodPost, "https://api.anonfiles.com/upload", buf)
    if err != nil {
        log.Fatal(err)
    }

    req.Header.Add("Content-Type", multipart.FormDataContentType())

    // The following line is not required because the http client will set it
    // because the request body is a bytes.Buffer.
    // req.ContentLength = int64(buf.Len())

    client := http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        log.Fatal(err)
    }

    defer resp.Body.Close()

    body, err := io.ReadAll(resp.Body)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(string(body))
}

它有效!

缺点是必须先将请求体复制到内存中。在我看来,这是不可避免的,因为它需要知道请求正文的大小。

今天关于《为什么使用 WaitGroup 时单个 goroutine 在上传文件过程中会发生死锁?》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>