[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"academy-blogs-en-1-1-all-context-golang-concurrent-tasks-all--*":3,"academy-blog-translations-x454dcpchnsrpek":79},{"data":4,"page":67,"perPage":67,"totalItems":67,"totalPages":67},[5],{"alt":6,"collectionId":7,"collectionName":8,"content":9,"cover_image":10,"cover_image_path":11,"created":12,"created_by":13,"expand":14,"id":73,"keywords":74,"locale":49,"published_at":75,"scheduled_at":13,"school_blog":71,"short_description":76,"slug":77,"status":69,"title":6,"updated":78,"updated_by":13,"views":72},"EP.62 Using Context in Golang to Manage Concurrent Tasks","sclblg987654321","school_blog_translations","\u003Cp>The Context package in Golang is crucial when working with concurrent tasks. It allows you to manage tasks, handle cancellations, and set timeouts for operations that may take an unknown or long period to complete. In this episode, we will learn how to use \u003Ccode inline=\"\">context\u003C\u002Fcode> to control multiple concurrent tasks and ensure they work together efficiently while giving us the ability to cancel or timeout tasks if needed. The use of \u003Ccode inline=\"\">context\u003C\u002Fcode> ensures that resources are freed properly and helps in building more scalable and manageable applications.\u003C\u002Fp>\u003Cp>&nbsp;\u003C\u002Fp>\u003Ch2>Why is the Context Package Important?\u003C\u002Fh2>\u003Cp>The Context package provides a way to manage long-running operations, particularly when dealing with multiple concurrent tasks. Here’s why it’s essential:\u003C\u002Fp>\u003Cul>\u003Cli>Cancellation of tasks: You can cancel tasks when they're no longer needed, such as when a user cancels an operation or when the server shuts down.\u003C\u002Fli>\u003Cli>Timeouts: Set time limits for operations to prevent them from running indefinitely.\u003C\u002Fli>\u003Cli>Passing information across goroutines: It allows you to pass metadata (e.g., deadlines or cancellation signals) between goroutines, making it easier to handle large and complex applications.\u003C\u002Fli>\u003C\u002Ful>\u003Ch3>Key Benefits:\u003C\u002Fh3>\u003Cul>\u003Cli>Improved resource management: Efficiently manages resources by ensuring timely cancellation and preventing memory leaks.\u003C\u002Fli>\u003Cli>Simplifies concurrency handling: Makes it easier to coordinate and control multiple goroutines in parallel operations.\u003C\u002Fli>\u003Cli>Easy cancellation and timeouts: It allows tasks to be canceled or timed out efficiently, preventing blocking and improving app performance.\u003C\u002Fli>\u003C\u002Ful>\u003Cp>&nbsp;\u003C\u002Fp>\u003Ch2>How the Context Package Works\u003C\u002Fh2>\u003Cp>The \u003Ccode inline=\"\">context\u003C\u002Fcode> package in Golang is designed to pass context information (like deadlines, cancellation signals, etc.) across multiple goroutines, making it an essential tool for managing concurrency.\u003C\u002Fp>\u003Ch3>Components of the Context Package:\u003C\u002Fh3>\u003Col>\u003Cli>Context Objects:\u003Cul>\u003Cli>\u003Ccode inline=\"\">context.Background()\u003C\u002Fcode> – The root context.\u003C\u002Fli>\u003Cli>\u003Ccode inline=\"\">context.TODO()\u003C\u002Fcode> – Used when it's unclear which context to use.\u003C\u002Fli>\u003Cli>\u003Ccode inline=\"\">context.WithCancel()\u003C\u002Fcode> – Creates a context with the ability to cancel it.\u003C\u002Fli>\u003Cli>\u003Ccode inline=\"\">context.WithTimeout()\u003C\u002Fcode> – Creates a context with a time limit.\u003C\u002Fli>\u003Cli>\u003Ccode inline=\"\">context.WithDeadline()\u003C\u002Fcode> – Creates a context with a specific deadline.\u003C\u002Fli>\u003C\u002Ful>\u003C\u002Fli>\u003Cli>Cancellation:\u003Cul>\u003Cli>You can cancel a context manually with \u003Ccode inline=\"\">cancel()\u003C\u002Fcode>, which will propagate the cancellation to any goroutine using that context.\u003C\u002Fli>\u003C\u002Ful>\u003C\u002Fli>\u003Cli>Timeouts and Deadlines:\u003Cul>\u003Cli>You can set a timeout for operations to prevent them from running indefinitely.\u003C\u002Fli>\u003C\u002Ful>\u003C\u002Fli>\u003C\u002Fol>\u003Cp>&nbsp;\u003C\u002Fp>\u003Ch2>How to Use Context for Concurrent Tasks in Golang\u003C\u002Fh2>\u003Cp>To use \u003Ccode inline=\"\">context\u003C\u002Fcode> with multiple concurrent tasks, you need to pass the context object to each goroutine you create so they can share cancellation signals and timeouts.\u003C\u002Fp>\u003Ch3>Steps to Implement Context in Concurrent Tasks:\u003C\u002Fh3>\u003Col>\u003Cli>Creating a Context:\u003Cbr>Use \u003Ccode inline=\"\">context.Background()\u003C\u002Fcode> or \u003Ccode inline=\"\">context.TODO()\u003C\u002Fcode> as the root context.\u003C\u002Fli>\u003Cli>Running Concurrent Tasks:\u003Cbr>When launching goroutines, pass the context object to them so they can observe cancellation signals.\u003C\u002Fli>\u003Cli>Handling Cancellation:\u003Cbr>Use \u003Ccode inline=\"\">context.WithCancel()\u003C\u002Fcode> to create a context that can be canceled. When canceling, all associated goroutines will also receive the cancellation signal.\u003C\u002Fli>\u003Cli>Timeouts:\u003Cbr>Use \u003Ccode inline=\"\">context.WithTimeout()\u003C\u002Fcode> to set a time limit for tasks. This prevents tasks from running indefinitely.\u003C\u002Fli>\u003C\u002Fol>\u003Cp>&nbsp;\u003C\u002Fp>\u003Ch2>Building the Code for Managing Concurrent Tasks Using Context\u003C\u002Fh2>\u003Cp>Let's see how we can use \u003Ccode inline=\"\">context\u003C\u002Fcode> to manage concurrent tasks efficiently.\u003C\u002Fp>\u003Cp>Example Code:\u003C\u002Fp>\u003Col>\u003Cli>\u003Ch3>Using \u003Ccode inline=\"\">context\u003C\u002Fcode> to Cancel Concurrent Tasks\u003C\u002Fh3>\u003C\u002Fli>\u003C\u002Fol>\u003Cpre>\u003Ccode class=\"language-plaintext language-go\">package main\n\nimport (\n    \"context\"\n    \"fmt\"\n    \"time\"\n)\n\nfunc task(ctx context.Context, id int) {\n    select {\n    case &lt;-time.After(2 * time.Second):  \u002F\u002F Simulate work\n        fmt.Printf(\"Task %d completed\\n\", id)\n    case &lt;-ctx.Done():  \u002F\u002F If the context is canceled\n        fmt.Printf(\"Task %d canceled\\n\", id)\n    }\n}\n\nfunc main() {\n    ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)\n    defer cancel()\n\n    for i := 1; i &lt;= 5; i++ {\n        go task(ctx, i)\n    }\n\n    time.Sleep(4 * time.Second) \u002F\u002F Wait for the tasks to finish or get canceled\n}\n\u003C\u002Fcode>\u003C\u002Fpre>\u003Cp>In this code, we create a context with a timeout of 3 seconds. The tasks will be canceled if they take longer than 3 seconds.\u003C\u002Fp>\u003Col start=\"2\">\u003Cli>\u003Ch3>Using Context with Cancellation for Long-Running Tasks\u003C\u002Fh3>\u003C\u002Fli>\u003C\u002Fol>\u003Cpre>\u003Ccode class=\"language-plaintext language-go\">package main\n\nimport (\n    \"context\"\n    \"fmt\"\n    \"time\"\n)\n\nfunc longRunningTask(ctx context.Context) {\n    for {\n        select {\n        case &lt;-time.After(1 * time.Second):\n            fmt.Println(\"Running task...\")\n        case &lt;-ctx.Done():  \u002F\u002F Detect cancellation\n            fmt.Println(\"Task canceled\")\n            return\n        }\n    }\n}\n\nfunc main() {\n    ctx, cancel := context.WithCancel(context.Background())\n\n    go longRunningTask(ctx)\n\n    time.Sleep(3 * time.Second)\n    cancel() \u002F\u002F Cancel the task after 3 seconds\n}\n\u003C\u002Fcode>\u003C\u002Fpre>\u003Cp>This example shows how to cancel a long-running task after 3 seconds using \u003Ccode inline=\"\">context.WithCancel()\u003C\u002Fcode>.\u003C\u002Fp>\u003Cp>&nbsp;\u003C\u002Fp>\u003Ch2>Testing Concurrent Tasks with Context\u003C\u002Fh2>\u003Cp>After implementing \u003Ccode inline=\"\">context\u003C\u002Fcode>, it's crucial to test that tasks are properly managed and canceled when needed.\u003C\u002Fp>\u003Ch3>Tests to Perform:\u003C\u002Fh3>\u003Cul>\u003Cli>Test task cancellation: Ensure that tasks are canceled when the context is canceled.\u003C\u002Fli>\u003Cli>Test timeout behavior: Ensure that tasks respect the timeouts set by the context.\u003C\u002Fli>\u003Cli>Test goroutine synchronization: Ensure that the goroutines are properly synchronized and behave as expected when canceled.\u003C\u002Fli>\u003C\u002Ful>\u003Cp>&nbsp;\u003C\u002Fp>\u003Chr>\u003Cp>&nbsp;\u003C\u002Fp>\u003Ch3>Challenge for Next EP!\u003C\u002Fh3>\u003Cp>Try implementing \u003Cstrong>the use of context in HTTP request handling\u003C\u002Fstrong> to manage timeouts and cancellations in web requests!\u003C\u002Fp>\u003Cp>&nbsp;\u003C\u002Fp>\u003Cp>\u003Cstrong>Next EP:\u003C\u002Fstrong>\u003Cbr>In the next episode, we will dive into \u003Cstrong>Creating a User Authentication System for WebSocket\u003C\u002Fstrong> to allow users to authenticate before accessing the chat rooms!\u003C\u002Fp>","96_11zon_rzeuvm16ht.webp","https:\u002F\u002Ftwsme-r2.tumwebsme.com\u002Fsclblg987654321\u002F068xdmnb9lw34gk\u002F96_11zon_rzeuvm16ht.webp","2026-03-04 08:48:26.135Z","",{"keywords":15,"locale":43,"school_blog":53},[16,23,28,33,38],{"collectionId":17,"collectionName":18,"created":19,"created_by":13,"id":20,"name":21,"updated":22,"updated_by":13},"sclkey987654321","school_keywords","2026-03-04 08:48:24.249Z","itgw0smx0evk3u7","Golang context","2026-04-10 16:13:46.706Z",{"collectionId":17,"collectionName":18,"created":24,"created_by":13,"id":25,"name":26,"updated":27,"updated_by":13},"2026-03-04 08:48:24.452Z","6295poaan1deg78","Concurrent tasks Golang","2026-04-10 16:13:46.837Z",{"collectionId":17,"collectionName":18,"created":29,"created_by":13,"id":30,"name":31,"updated":32,"updated_by":13},"2026-03-04 08:48:24.660Z","mtuvs8j3fi835at","Goroutines management","2026-04-10 16:13:46.966Z",{"collectionId":17,"collectionName":18,"created":34,"created_by":13,"id":35,"name":36,"updated":37,"updated_by":13},"2026-03-04 08:48:24.863Z","9hk5a7dzhl4f43w","Golang task cancellation","2026-04-10 16:13:47.101Z",{"collectionId":17,"collectionName":18,"created":39,"created_by":13,"id":40,"name":41,"updated":42,"updated_by":13},"2026-03-04 08:45:35.456Z","p12faqv7fmetlja","Golang timeouts","2026-04-10 16:13:00.381Z",{"code":44,"collectionId":45,"collectionName":46,"created":47,"flag":48,"id":49,"is_default":50,"label":51,"updated":52},"en","pbc_1989393366","locales","2026-01-22 11:00:02.726Z","twemoji:flag-united-states","qv9c1llfov2d88z",false,"English","2026-04-10 15:42:46.825Z",{"category":54,"collectionId":55,"collectionName":56,"expand":57,"id":71,"views":72},"wqxt7ag2gn7xcmk","pbc_2105096300","school_blogs",{"category":58},{"blogIds":59,"collectionId":60,"collectionName":61,"created":62,"created_by":13,"id":54,"image":63,"image_alt":13,"image_path":64,"label":65,"name":66,"priority":67,"publish_at":68,"scheduled_at":13,"status":69,"updated":70,"updated_by":13},[],"sclcatblg987654321","school_category_blogs","2026-03-04 08:33:53.210Z","59ty92ns80w_15oc1implw.png","https:\u002F\u002Ftwsme-r2.tumwebsme.com\u002Fsclcatblg987654321\u002Fwqxt7ag2gn7xcmk\u002F59ty92ns80w_15oc1implw.png",{"en":66,"th":66},"Golang The Series",1,"2026-03-16 04:39:38.440Z","published","2026-04-25 02:32:15.470Z","x454dcpchnsrpek",210,"068xdmnb9lw34gk",[20,25,30,35,40],"2025-07-07 03:34:30.118Z","Learn how to use Context in Golang to manage concurrent tasks, control their execution, and handle cancellation or timeouts efficiently.","context-golang-concurrent-tasks","2026-04-22 07:10:10.801Z",{"en":77}]