{"id":41791,"date":"2024-12-01T10:50:28","date_gmt":"2024-12-01T02:50:28","guid":{"rendered":"https:\/\/fwq.ai\/blog\/41791\/"},"modified":"2024-12-01T10:50:28","modified_gmt":"2024-12-01T02:50:28","slug":"goroutine-%e5%81%9c%e6%ad%a2%e6%ad%a3%e5%9c%a8%e8%bf%90%e8%a1%8c%e7%9a%84%e8%bf%9b%e7%a8%8b","status":"publish","type":"post","link":"https:\/\/fwq.ai\/blog\/41791\/","title":{"rendered":"Goroutine-\u505c\u6b62\u6b63\u5728\u8fd0\u884c\u7684\u8fdb\u7a0b"},"content":{"rendered":"<p><b><\/b> <\/p>\n<p>\u5f53\u524d\u4f4d\u7f6e\uff1a <span>&gt;<\/span>  <span>&gt;<\/span>  <span>&gt;<\/span>  <span>&gt;<\/span> <span>Goroutine-\u505c\u6b62\u6b63\u5728\u8fd0\u884c\u7684\u8fdb\u7a0b<\/span><\/p>\n<h1>Goroutine-\u505c\u6b62\u6b63\u5728\u8fd0\u884c\u7684\u8fdb\u7a0b<\/h1>\n<p><span>\u6765\u6e90\uff1astackoverflow<\/span><br \/>\n<span>2024-04-21 15:12:32<\/span><br \/>\n<span><i><\/i>0\u6d4f\u89c8<\/span><br \/>\n<span style=\"cursor: pointer\"><i><\/i>\u6536\u85cf<\/span> <\/p>\n<p><span style=\"color: #FF6600;, Helvetica, Arial, sans-serif;font-size: 14px;background-color: #FFFFFF\">Golang<\/span>\u4e0d\u77e5\u9053\u5927\u5bb6\u662f\u5426\u719f\u6089\uff1f\u4eca\u5929\u6211\u5c06\u7ed9\u5927\u5bb6\u4ecb\u7ecd<span style=\"color: #FF6600;, Helvetica, Arial, sans-serif;font-size: 14px;background-color: #FFFFFF\">\u300aGoroutine-\u505c\u6b62\u6b63\u5728\u8fd0\u884c\u7684\u8fdb\u7a0b\u300b<\/span>\uff0c\u8fd9\u7bc7\u6587\u7ae0\u4e3b\u8981\u4f1a\u8bb2\u5230<span style=\"color: #FF6600;, Helvetica, Arial, sans-serif;font-size: 14px;background-color: #FFFFFF\"><\/span>\u7b49\u7b49\u77e5\u8bc6\u70b9\uff0c\u5982\u679c\u4f60\u5728\u770b\u5b8c\u672c\u7bc7\u6587\u7ae0\u540e\uff0c\u6709\u66f4\u597d\u7684\u5efa\u8bae\u6216\u8005\u53d1\u73b0\u54ea\u91cc\u6709\u95ee\u9898\uff0c\u5e0c\u671b\u5927\u5bb6\u90fd\u80fd\u79ef\u6781\u8bc4\u8bba\u6307\u51fa\uff0c\u8c22\u8c22\uff01\u5e0c\u671b\u6211\u4eec\u80fd\u4e00\u8d77\u52a0\u6cb9\u8fdb\u6b65\uff01<\/p>\n<p> \u95ee\u9898\u5185\u5bb9<br \/>\n <\/p>\n<p>\u6211\u4f7f\u7528\u4ee5\u4e0b\u4ee3\u7801\uff0c\u5728\u5927\u591a\u6570\u60c5\u51b5\u4e0b\u90fd\u53ef\u4ee5\u6b63\u5e38\u5de5\u4f5c\uff0c\u4ee5\u9632\u6211\u4eec\u4f7f\u7528\u4e00\u4e9b\u957f\u65f6\u95f4\u8fd0\u884c\u7684\u8fdb\u7a0b\uff0c\u8be5\u8fdb\u7a0b\u4e0d\u4f1a\u5728\u7a0b\u5e8f\u5185\u505c\u6b62<strong>\u4e0d\u4f1a<\/strong>\u7ed3\u675f\uff08\u8fd9\u91cc\u6211\u5c06\u65f6\u95f4\u9650\u5236\u4e3a 60 \u79d2\uff09\u793a\u4f8b\uff09<\/p>\n<p>\u6211\u5e0c\u671b\u6bcf\u4e2a\u4f5c\u4e1a\u90fd\u4f1a\u5728<strong>5\u79d2<\/strong>\u540e\u7ec8\u6b62\uff08\u5373\u4f7f\u5b83\u6ca1\u6709\u5b8c\u6210\u5de5\u4f5c\u4e5f\u7ec8\u6b62\u8fdb\u7a0b\uff09\uff0c \u5982\u4f55<strong>\u4e0d<\/strong><strong>\u66f4\u6539<\/strong>\u51fd\u6570 <code>mylongrunningfunc<\/code> \u6765\u505a\u5230\u8fd9\u4e00\u70b9\u3002<\/p>\n<p>\u6211\u77e5\u9053\u5728 go \u4e2d\u89e3\u51b3\u8fd9\u4e2a\u95ee\u9898\u5e76\u4e0d\u7b80\u5355\uff0c\u6709\u4ec0\u4e48\u6211\u53ef\u4ee5\u4f7f\u7528\u7684<strong>\u6280\u5de7<\/strong>\u5417\uff1f<\/p>\n<p>\u8fd9\u662f\u4e00\u4e9b\u6700\u5c0f\u7684\u53ef\u91cd\u73b0\u793a\u4f8b<\/p>\n<p>https:\/\/play.golang.org\/p\/a0rwy4bywmt<\/p>\n<pre>package main\n\nimport (\n    \"context\"\n    \"errors\"\n    \"fmt\"\n    \"time\"\n\n    \"github.com\/gammazero\/workerpool\"\n)\n\nfunc main() {\n    \/\/ here define a timeout for 5 sec,\n    \/\/ the task should be terminate after 5 sec\n    ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)\n    defer cancel()\n\n    runner := newRunner(ctx, 10)\n\n    runner.do(job{\n        Name: \"a\",\n        Task: func() jobResult {\n            select {\n            case &lt;-ctx.Done():\n                return jobResult{Error: errors.New(\"Timedout, exiting\")}\n            default:\n                myLongRunningFunc(\"A job\")\n            }\n            return jobResult{Data: \"from a\"}\n        },\n    })\n\n    runner.do(job{\n        Name: \"b\",\n        Task: func() jobResult {\n            select {\n            case &lt;-ctx.Done():\n                return jobResult{Error: errors.New(\"Timeouts, exiting\")}\n            default:\n                myLongRunningFunc(\"B job\")\n            }\n\n            return jobResult{Data: \"from b\"}\n        },\n    })\n\n    results := runner.getjobResults()\n    fmt.Println(results)\n    time.Sleep(time.Second * 60)\n}\n\nfunc myLongRunningFunc(name string) {\n    for i := 0; i &lt; 100000; i++ {\n        time.Sleep(time.Second * 1)\n        msg := \"job\" + name + \" running..\\n\"\n        fmt.Println(msg)\n    }\n}\n\ntype runner struct {\n    *workerpool.WorkerPool\n    ctx     context.Context\n    kill    chan struct{}\n    result  chan jobResult\n    results []jobResult\n}\n\nfunc (r *runner) processResults() {\n    for {\n        select {\n        case res, ok := &lt;-r.result:\n            if !ok {\n                goto Done\n            }\n            r.results = append(r.results, res)\n        }\n    }\nDone:\n    &lt;-r.kill\n}\n\nfunc newRunner(ctx context.Context, numRunners int) *runner {\n    r := &amp;runner{\n        WorkerPool: workerpool.New(numRunners),\n        ctx:        ctx,\n        kill:       make(chan struct{}),\n        result:     make(chan jobResult),\n    }\n    go r.processResults()\n    return r\n}\n\nfunc (r *runner) do(j job) {\n    r.Submit(r.wrap(&amp;j))\n}\n\nfunc (r *runner) getjobResults() []jobResult {\n    r.StopWait()\n    close(r.result)\n    r.kill &lt;- struct{}{}\n    return r.results\n}\n\nfunc (r *runner) wrap(job *job) func() {\n    return func() {\n        job.result = make(chan jobResult)\n        go job.Run()\n        select {\n        case res := &lt;-job.result:\n            r.result &lt;- res\n        case &lt;-r.ctx.Done():\n            fmt.Printf(\"Job '%s' should stop here\\n\", job.Name)\n            r.result &lt;- jobResult{name: job.Name, Error: r.ctx.Err()}\n        }\n    }\n}\n\ntype job struct {\n    Name    string\n    Task    func() jobResult\n    Context context.Context\n    result  chan jobResult\n    stopped chan struct{}\n    done    context.CancelFunc\n}\n\nfunc (j *job) Run() {\n    result := j.Task()\n    result.name = j.Name\n    j.result &lt;- result\n}\n\ntype jobResult struct {\n    name  string\n    Error error\n    Data  interface{}\n}<\/pre>\n<p>\u7531\u4e8e\u6211\u4f7f\u7528chancel\u9891\u9053\uff0c\u56e0\u6b64\u7f16\u8f91\u4e0d\u76f8\u5173<\/p>\n<p> <\/p>\n<h2>\u89e3\u51b3\u65b9\u6848<\/h2>\n<p> <\/p>\n<p>\u6211\u5e0c\u671b\u6bcf\u4e2a\u4f5c\u4e1a\u90fd\u88ab\u7ec8\u6b62\uff08\u6740\u6b7b\u8fdb\u7a0b\uff0c\u5373\u4f7f\u5b83\u662f \u6ca1\u6709\u5b8c\u6210\u5de5\u4f5c\uff095\u79d2\u540e\uff0c\u6211\u600e\u6837\u624d\u80fd\u5728\u4e0d\u6539\u53d8\u7684\u60c5\u51b5\u4e0b\u5b8c\u6210\u5b83 \u51fd\u6570 mylongrunningfunc\u3002<\/p>\n<p>\u7136\u540e\u4f60\u53ea\u9700\u6dfb\u52a0\u4e00\u4e2a5\u79d2\u7684\u670d\u52a1\u5458\u7136\u540e\u9000\u51fa\u3002<\/p>\n<pre>package main\n\nimport (\n    \"context\"\n    \"errors\"\n    \"fmt\"\n    \"time\"\n\n    \"github.com\/gammazero\/workerpool\"\n)\n\nfunc main() {\n    go func() {\n        \/\/ here define a timeout for 5 sec,\n        \/\/ the task should be terminate after 5 sec\n        ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)\n        defer cancel()\n\n        runner := newRunner(ctx, 10)\n\n        runner.do(job{\n            Name: \"a\",\n            Task: func() jobResult {\n                select {\n                case &lt;-ctx.Done():\n                    return jobResult{Error: errors.New(\"Timedout, exiting\")}\n                default:\n                    myLongRunningFunc(\"A job\")\n                }\n                return jobResult{Data: \"from a\"}\n            },\n        })\n\n        runner.do(job{\n            Name: \"b\",\n            Task: func() jobResult {\n                select {\n                case &lt;-ctx.Done():\n                    return jobResult{Error: errors.New(\"Timeouts, exiting\")}\n                default:\n                    myLongRunningFunc(\"B job\")\n                }\n\n                return jobResult{Data: \"from b\"}\n            },\n        })\n\n        results := runner.getjobResults()\n        fmt.Println(results)\n        time.Sleep(time.Second * 60)\n    }()\n    &lt;-time.After(time.Second * 5)\n}\n\nfunc myLongRunningFunc(name string) {\n    for i := 0; i &lt; 100000; i++ {\n        time.Sleep(time.Second * 1)\n        msg := \"job\" + name + \" running..\\n\"\n        fmt.Println(msg)\n    }\n}\n\ntype runner struct {\n    *workerpool.WorkerPool\n    ctx     context.Context\n    kill    chan struct{}\n    result  chan jobResult\n    results []jobResult\n}\n\nfunc (r *runner) processResults() {\n    for {\n        select {\n        case res, ok := &lt;-r.result:\n            if !ok {\n                goto Done\n            }\n            r.results = append(r.results, res)\n        }\n    }\nDone:\n    &lt;-r.kill\n}\n\nfunc newRunner(ctx context.Context, numRunners int) *runner {\n    r := &amp;runner{\n        WorkerPool: workerpool.New(numRunners),\n        ctx:        ctx,\n        kill:       make(chan struct{}),\n        result:     make(chan jobResult),\n    }\n    go r.processResults()\n    return r\n}\n\nfunc (r *runner) do(j job) {\n    r.Submit(r.wrap(&amp;j))\n}\n\nfunc (r *runner) getjobResults() []jobResult {\n    r.StopWait()\n    close(r.result)\n    r.kill &lt;- struct{}{}\n    return r.results\n}\n\nfunc (r *runner) wrap(job *job) func() {\n    return func() {\n        job.result = make(chan jobResult)\n        go job.Run()\n        select {\n        case res := &lt;-job.result:\n            r.result &lt;- res\n        case &lt;-r.ctx.Done():\n            fmt.Printf(\"Job '%s' should stop here\\n\", job.Name)\n            r.result &lt;- jobResult{name: job.Name, Error: r.ctx.Err()}\n        }\n    }\n}\n\ntype job struct {\n    Name    string\n    Task    func() jobResult\n    Context context.Context\n    result  chan jobResult\n    stopped chan struct{}\n    done    context.CancelFunc\n}\n\nfunc (j *job) Run() {\n    result := j.Task()\n    result.name = j.Name\n    j.result &lt;- result\n}\n\ntype jobResult struct {\n    name  string\n    Error error\n    Data  interface{}\n}<\/pre>\n<p>\u6211\u8ba4\u4e3a\u4e0d\u53ef\u80fd\u4ece\u5916\u90e8 goroutine \u505c\u6b62 goroutine\u3002\u60a8\u53ef\u4ee5\u68c0\u67e5\u5b83\u662f\u5426\u8d85\u65f6\uff0c\u4f46\u662f\u60a8\u65e0\u6cd5\u963b\u6b62\u5b83\u3002<\/p>\n<p>\u60a8\u53ef\u4ee5\u505a\u7684\u662f\u901a\u8fc7\u901a\u9053\u5411 goroutine \u53d1\u9001\u4e00\u6761\u6d88\u606f\uff0c\u8be5\u6d88\u606f\u53ef\u4ee5\u88ab\u76d1\u89c6\u5e76\u5728\u8fd9\u79cd\u60c5\u51b5\u4e0b\u505c\u6b62\u3002<\/p>\n<\/p>\n<p>\u4eca\u5929\u5173\u4e8e\u300aGoroutine-\u505c\u6b62\u6b63\u5728\u8fd0\u884c\u7684\u8fdb\u7a0b\u300b\u7684\u5185\u5bb9\u4ecb\u7ecd\u5c31\u5230\u6b64\u7ed3\u675f\uff0c\u5982\u679c\u6709\u4ec0\u4e48\u7591\u95ee\u6216\u8005\u5efa\u8bae\uff0c\u53ef\u4ee5\u5728\u7c73\u4e91\u516c\u4f17\u53f7\u4e0b\u591a\u591a\u56de\u590d\u4ea4\u6d41\uff1b\u6587\u4e2d\u82e5\u6709\u4e0d\u6b63\u4e4b\u5904\uff0c\u4e5f\u5e0c\u671b\u56de\u590d\u7559\u8a00\u4ee5\u544a\u77e5\uff01<\/p>\n","protected":false},"excerpt":{"rendered":"<p>\u5f53\u524d\u4f4d\u7f6e\uff1a &gt; &gt; &gt; &gt; Goroutine-\u505c\u6b62\u6b63\u5728\u8fd0\u884c\u7684\u8fdb\u7a0b Goroutine-\u505c\u6b62\u6b63\u5728\u8fd0\u884c\u7684\u8fdb\u7a0b \u6765\u6e90\uff1astackoverflow 2024-04-21 15:12:32 0\u6d4f\u89c8 \u6536\u85cf Golang\u4e0d\u77e5\u9053\u5927\u5bb6\u662f\u5426\u719f\u6089\uff1f\u4eca\u5929\u6211\u5c06\u7ed9\u5927\u5bb6\u4ecb\u7ecd\u300aGoroutine-\u505c\u6b62\u6b63\u5728\u8fd0\u884c\u7684\u8fdb\u7a0b\u300b\uff0c\u8fd9\u7bc7\u6587\u7ae0\u4e3b\u8981\u4f1a\u8bb2\u5230\u7b49\u7b49\u77e5\u8bc6\u70b9\uff0c\u5982\u679c\u4f60\u5728\u770b\u5b8c\u672c\u7bc7\u6587\u7ae0\u540e\uff0c\u6709\u66f4\u597d\u7684\u5efa\u8bae\u6216\u8005\u53d1\u73b0\u54ea\u91cc\u6709\u95ee\u9898\uff0c\u5e0c\u671b\u5927\u5bb6\u90fd\u80fd\u79ef\u6781\u8bc4\u8bba\u6307\u51fa\uff0c\u8c22\u8c22\uff01\u5e0c\u671b\u6211\u4eec\u80fd\u4e00\u8d77\u52a0\u6cb9\u8fdb\u6b65\uff01 \u95ee\u9898\u5185\u5bb9 \u6211\u4f7f\u7528\u4ee5\u4e0b\u4ee3\u7801\uff0c\u5728\u5927\u591a\u6570\u60c5\u51b5\u4e0b\u90fd\u53ef\u4ee5\u6b63\u5e38\u5de5\u4f5c\uff0c\u4ee5\u9632\u6211\u4eec\u4f7f\u7528\u4e00\u4e9b\u957f\u65f6\u95f4\u8fd0\u884c\u7684\u8fdb\u7a0b\uff0c\u8be5\u8fdb\u7a0b\u4e0d\u4f1a\u5728\u7a0b\u5e8f\u5185\u505c\u6b62\u4e0d\u4f1a\u7ed3\u675f\uff08\u8fd9\u91cc\u6211\u5c06\u65f6\u95f4\u9650\u5236\u4e3a 60 \u79d2\uff09\u793a\u4f8b\uff09 \u6211\u5e0c\u671b\u6bcf\u4e2a\u4f5c\u4e1a\u90fd\u4f1a\u57285\u79d2\u540e\u7ec8\u6b62\uff08\u5373\u4f7f\u5b83\u6ca1\u6709\u5b8c\u6210\u5de5\u4f5c\u4e5f\u7ec8\u6b62\u8fdb\u7a0b\uff09\uff0c \u5982\u4f55\u4e0d\u66f4\u6539\u51fd\u6570 mylongrunningfunc \u6765\u505a\u5230\u8fd9\u4e00\u70b9\u3002 \u6211\u77e5\u9053\u5728 go \u4e2d\u89e3\u51b3\u8fd9\u4e2a\u95ee\u9898\u5e76\u4e0d\u7b80\u5355\uff0c\u6709\u4ec0\u4e48\u6211\u53ef\u4ee5\u4f7f\u7528\u7684\u6280\u5de7\u5417\uff1f \u8fd9\u662f\u4e00\u4e9b\u6700\u5c0f\u7684\u53ef\u91cd\u73b0\u793a\u4f8b https:\/\/play.golang.org\/p\/a0rwy4bywmt package main import ( &#8220;context&#8221; &#8220;errors&#8221; &#8220;fmt&#8221; &#8220;time&#8221; &#8220;github.com\/gammazero\/workerpool&#8221; ) func main() { \/\/ here define a timeout for 5 sec, \/\/ the task should be terminate after 5 [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[17],"tags":[],"class_list":["post-41791","post","type-post","status-publish","format-standard","hentry","category-docker"],"_links":{"self":[{"href":"https:\/\/fwq.ai\/blog\/wp-json\/wp\/v2\/posts\/41791","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/fwq.ai\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/fwq.ai\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/fwq.ai\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/fwq.ai\/blog\/wp-json\/wp\/v2\/comments?post=41791"}],"version-history":[{"count":0,"href":"https:\/\/fwq.ai\/blog\/wp-json\/wp\/v2\/posts\/41791\/revisions"}],"wp:attachment":[{"href":"https:\/\/fwq.ai\/blog\/wp-json\/wp\/v2\/media?parent=41791"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/fwq.ai\/blog\/wp-json\/wp\/v2\/categories?post=41791"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/fwq.ai\/blog\/wp-json\/wp\/v2\/tags?post=41791"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}