{"id":13604,"date":"2022-10-04T16:32:06","date_gmt":"2022-10-04T11:02:06","guid":{"rendered":"https:\/\/jassweb.com\/solved\/solved-unexpected-behavior-from-launching-a-method-call-on-a-loop-variable-as-a-goroutine\/"},"modified":"2022-10-04T16:32:06","modified_gmt":"2022-10-04T11:02:06","slug":"solved-unexpected-behavior-from-launching-a-method-call-on-a-loop-variable-as-a-goroutine","status":"publish","type":"post","link":"https:\/\/jassweb.com\/solved\/solved-unexpected-behavior-from-launching-a-method-call-on-a-loop-variable-as-a-goroutine\/","title":{"rendered":"[Solved] Unexpected behavior from launching a method call on a loop variable as a goroutine"},"content":{"rendered":"<p> [ad_1]<br \/>\n<\/p>\n<div id=\"answer-68429388\" class=\"answer js-answer accepted-answer js-accepted-answer\" data-answerid=\"68429388\" data-parentid=\"68428437\" data-score=\"3\" data-position-on-page=\"1\" data-highest-scored=\"1\" data-question-has-accepted-highest-score=\"1\" itemprop=\"acceptedAnswer\" itemscope itemtype=\"https:\/\/schema.org\/Answer\">\n<div class=\"post-layout\">\n<div class=\"votecell post-layout--left\"><\/div>\n<div class=\"answercell post-layout--right\">\n<div class=\"s-prose js-post-body\" itemprop=\"text\">\n<h2 id=\"problem-21n9\">Problem<\/h2>\n<p>Your first version has a <em>synchronisation bug<\/em>, which manifests itself as a <em>data race<\/em>:<\/p>\n<pre><code>$ go run -race main.go\n0 (PrintAddr): 0xc0000b4018\n0 (PrintAddr): 0xc0000c2120\n==================\nWARNING: DATA RACE\nWrite at 0x00c0000b4018 by main goroutine:\n  main.main()\n      redacted\/main.go:29 +0x1e5\n\nPrevious read at 0x00c0000b4018 by goroutine 7:\n  main.(*User).PrintAddr()\n      redacted\/main.go:19 +0x44\n\nGoroutine 7 (finished) created at:\n  main.main()\n      redacted\/main.go:30 +0x244\n==================\n1 (PrintAddr): 0xc0000b4018\n1 (PrintAddr): 0xc0000c2138\n2 (PrintAddr): 0xc0000b4018\n2 (PrintAddr): 0xc0000c2150\n3 (PrintAddr): 0xc0000b4018\n3 (PrintAddr): 0xc0000c2168\nFound 1 data race(s)\n<\/code><\/pre>\n<p>The <code>for<\/code> loop (line 29) keeps updating loop variable <code>user<\/code> <em>while<\/em> (i.e. in a concurrent manner without proper synchronisation) the <code>PrintAddr<\/code> method accesses it via its pointer receiver (line 19). Note that if you don&#8217;t start <code>user.PrintAddr()<\/code> as a goroutine on line 30, the problem goes away.<\/p>\n<p>The problem and a solution to it are actually given at the bottom of <a rel=\"nofollow noopener\" target=\"_blank\" href=\"https:\/\/github.com\/golang\/go\/wiki\/CommonMistakes#using-goroutines-on-loop-iterator-variables\">the Wiki you link to<\/a>.<\/p>\n<blockquote>\n<p>But why did the situation in the article not apply here and I didn&#8217;t get many <code>3 (PrintAddr)<\/code> instead?<\/p>\n<\/blockquote>\n<p>That synchronisation bug is a source of undesired undeterminism. In particular, you cannot predict how many times (if any) <code>3 (PrintAddr)<\/code> will be printed, and that number may vary from one execution to the next. In fact, scroll up and see for yourself: in my execution with the race detector on, the output happened to feature two of each integer between 0 and 3, despite the bug; but there&#8217;s no guarantee for that.<\/p>\n<h2 id=\"solution-fviw\">Solution<\/h2>\n<p>Simply shadow loop variable <code>user<\/code> at the top of the loop and the problem goes away:<\/p>\n<pre><code>for i, user := range users {\n    user := user \/\/ &lt;---\n    go user.PrintAddr()\n    go users[i].PrintAddr()\n}\n<\/code><\/pre>\n<p><code>PrintAddr<\/code> will now operate on the innermost <code>user<\/code> variable, which is not updated by the <code>for<\/code> loop on line 29.<\/p>\n<p>(<a rel=\"nofollow noopener\" target=\"_blank\" href=\"https:\/\/play.golang.org\/p\/o3CQ2zlHFfZ\">Playground<\/a>)<\/p>\n<h3 id=\"addendum-roo2\">Addendum<\/h3>\n<p>You should also use a wait group to wait for all your goroutines to finish. <code>time.Sleep<\/code> is no way to coordinate goroutines.<\/p>\n<\/p><\/div>\n<div class=\"mt24\"><\/div>\n<\/div>\n<p>            <span class=\"d-none\" itemprop=\"commentCount\">1<\/span> <\/p><\/div>\n<\/div>\n<p>[ad_2]<\/p>\n<p>solved Unexpected behavior from launching a method call on a loop variable as a goroutine <\/p>\n","protected":false},"excerpt":{"rendered":"<p>[ad_1] Problem Your first version has a synchronisation bug, which manifests itself as a data race: $ go run -race main.go 0 (PrintAddr): 0xc0000b4018 0 (PrintAddr): 0xc0000c2120 ================== WARNING: DATA RACE Write at 0x00c0000b4018 by main goroutine: main.main() redacted\/main.go:29 +0x1e5 Previous read at 0x00c0000b4018 by goroutine 7: main.(*User).PrintAddr() redacted\/main.go:19 +0x44 Goroutine 7 (finished) created at: &#8230; <a title=\"[Solved] Unexpected behavior from launching a method call on a loop variable as a goroutine\" class=\"read-more\" href=\"https:\/\/jassweb.com\/solved\/solved-unexpected-behavior-from-launching-a-method-call-on-a-loop-variable-as-a-goroutine\/\" aria-label=\"More on [Solved] Unexpected behavior from launching a method call on a loop variable as a goroutine\">Read more<\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[320],"tags":[3627,596,2187,391,712],"class_list":["post-13604","post","type-post","status-publish","format-standard","hentry","category-solved","tag-data-race","tag-go","tag-goroutine","tag-loops","tag-pointers"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.5 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>[Solved] Unexpected behavior from launching a method call on a loop variable as a goroutine - JassWeb<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/jassweb.com\/solved\/solved-unexpected-behavior-from-launching-a-method-call-on-a-loop-variable-as-a-goroutine\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"[Solved] Unexpected behavior from launching a method call on a loop variable as a goroutine - JassWeb\" \/>\n<meta property=\"og:description\" content=\"[ad_1] Problem Your first version has a synchronisation bug, which manifests itself as a data race: $ go run -race main.go 0 (PrintAddr): 0xc0000b4018 0 (PrintAddr): 0xc0000c2120 ================== WARNING: DATA RACE Write at 0x00c0000b4018 by main goroutine: main.main() redacted\/main.go:29 +0x1e5 Previous read at 0x00c0000b4018 by goroutine 7: main.(*User).PrintAddr() redacted\/main.go:19 +0x44 Goroutine 7 (finished) created at: ... Read more\" \/>\n<meta property=\"og:url\" content=\"https:\/\/jassweb.com\/solved\/solved-unexpected-behavior-from-launching-a-method-call-on-a-loop-variable-as-a-goroutine\/\" \/>\n<meta property=\"og:site_name\" content=\"JassWeb\" \/>\n<meta property=\"article:published_time\" content=\"2022-10-04T11:02:06+00:00\" \/>\n<meta name=\"author\" content=\"Kirat\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Kirat\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"2 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/jassweb.com\/solved\/solved-unexpected-behavior-from-launching-a-method-call-on-a-loop-variable-as-a-goroutine\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/jassweb.com\/solved\/solved-unexpected-behavior-from-launching-a-method-call-on-a-loop-variable-as-a-goroutine\/\"},\"author\":{\"name\":\"Kirat\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31\"},\"headline\":\"[Solved] Unexpected behavior from launching a method call on a loop variable as a goroutine\",\"datePublished\":\"2022-10-04T11:02:06+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/jassweb.com\/solved\/solved-unexpected-behavior-from-launching-a-method-call-on-a-loop-variable-as-a-goroutine\/\"},\"wordCount\":251,\"publisher\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#organization\"},\"keywords\":[\"data-race\",\"go\",\"goroutine\",\"loops\",\"pointers\"],\"articleSection\":[\"Solved\"],\"inLanguage\":\"en-US\"},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/jassweb.com\/solved\/solved-unexpected-behavior-from-launching-a-method-call-on-a-loop-variable-as-a-goroutine\/\",\"url\":\"https:\/\/jassweb.com\/solved\/solved-unexpected-behavior-from-launching-a-method-call-on-a-loop-variable-as-a-goroutine\/\",\"name\":\"[Solved] Unexpected behavior from launching a method call on a loop variable as a goroutine - JassWeb\",\"isPartOf\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#website\"},\"datePublished\":\"2022-10-04T11:02:06+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/jassweb.com\/solved\/solved-unexpected-behavior-from-launching-a-method-call-on-a-loop-variable-as-a-goroutine\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/jassweb.com\/solved\/solved-unexpected-behavior-from-launching-a-method-call-on-a-loop-variable-as-a-goroutine\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/jassweb.com\/solved\/solved-unexpected-behavior-from-launching-a-method-call-on-a-loop-variable-as-a-goroutine\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/jassweb.com\/solved\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"[Solved] Unexpected behavior from launching a method call on a loop variable as a goroutine\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/jassweb.com\/solved\/#website\",\"url\":\"https:\/\/jassweb.com\/solved\/\",\"name\":\"JassWeb\",\"description\":\"Build High-quality Websites\",\"publisher\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/jassweb.com\/solved\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/jassweb.com\/solved\/#organization\",\"name\":\"Jass Web\",\"url\":\"https:\/\/jassweb.com\/solved\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png\",\"contentUrl\":\"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png\",\"width\":693,\"height\":132,\"caption\":\"Jass Web\"},\"image\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/\"}},{\"@type\":\"Person\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31\",\"name\":\"Kirat\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1775798750\",\"contentUrl\":\"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1775798750\",\"caption\":\"Kirat\"},\"sameAs\":[\"http:\/\/jassweb.com\"],\"url\":\"https:\/\/jassweb.com\/solved\/author\/jaspritsinghghumangmail-com\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"[Solved] Unexpected behavior from launching a method call on a loop variable as a goroutine - JassWeb","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/jassweb.com\/solved\/solved-unexpected-behavior-from-launching-a-method-call-on-a-loop-variable-as-a-goroutine\/","og_locale":"en_US","og_type":"article","og_title":"[Solved] Unexpected behavior from launching a method call on a loop variable as a goroutine - JassWeb","og_description":"[ad_1] Problem Your first version has a synchronisation bug, which manifests itself as a data race: $ go run -race main.go 0 (PrintAddr): 0xc0000b4018 0 (PrintAddr): 0xc0000c2120 ================== WARNING: DATA RACE Write at 0x00c0000b4018 by main goroutine: main.main() redacted\/main.go:29 +0x1e5 Previous read at 0x00c0000b4018 by goroutine 7: main.(*User).PrintAddr() redacted\/main.go:19 +0x44 Goroutine 7 (finished) created at: ... Read more","og_url":"https:\/\/jassweb.com\/solved\/solved-unexpected-behavior-from-launching-a-method-call-on-a-loop-variable-as-a-goroutine\/","og_site_name":"JassWeb","article_published_time":"2022-10-04T11:02:06+00:00","author":"Kirat","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Kirat","Est. reading time":"2 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/jassweb.com\/solved\/solved-unexpected-behavior-from-launching-a-method-call-on-a-loop-variable-as-a-goroutine\/#article","isPartOf":{"@id":"https:\/\/jassweb.com\/solved\/solved-unexpected-behavior-from-launching-a-method-call-on-a-loop-variable-as-a-goroutine\/"},"author":{"name":"Kirat","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31"},"headline":"[Solved] Unexpected behavior from launching a method call on a loop variable as a goroutine","datePublished":"2022-10-04T11:02:06+00:00","mainEntityOfPage":{"@id":"https:\/\/jassweb.com\/solved\/solved-unexpected-behavior-from-launching-a-method-call-on-a-loop-variable-as-a-goroutine\/"},"wordCount":251,"publisher":{"@id":"https:\/\/jassweb.com\/solved\/#organization"},"keywords":["data-race","go","goroutine","loops","pointers"],"articleSection":["Solved"],"inLanguage":"en-US"},{"@type":"WebPage","@id":"https:\/\/jassweb.com\/solved\/solved-unexpected-behavior-from-launching-a-method-call-on-a-loop-variable-as-a-goroutine\/","url":"https:\/\/jassweb.com\/solved\/solved-unexpected-behavior-from-launching-a-method-call-on-a-loop-variable-as-a-goroutine\/","name":"[Solved] Unexpected behavior from launching a method call on a loop variable as a goroutine - JassWeb","isPartOf":{"@id":"https:\/\/jassweb.com\/solved\/#website"},"datePublished":"2022-10-04T11:02:06+00:00","breadcrumb":{"@id":"https:\/\/jassweb.com\/solved\/solved-unexpected-behavior-from-launching-a-method-call-on-a-loop-variable-as-a-goroutine\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/jassweb.com\/solved\/solved-unexpected-behavior-from-launching-a-method-call-on-a-loop-variable-as-a-goroutine\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/jassweb.com\/solved\/solved-unexpected-behavior-from-launching-a-method-call-on-a-loop-variable-as-a-goroutine\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/jassweb.com\/solved\/"},{"@type":"ListItem","position":2,"name":"[Solved] Unexpected behavior from launching a method call on a loop variable as a goroutine"}]},{"@type":"WebSite","@id":"https:\/\/jassweb.com\/solved\/#website","url":"https:\/\/jassweb.com\/solved\/","name":"JassWeb","description":"Build High-quality Websites","publisher":{"@id":"https:\/\/jassweb.com\/solved\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/jassweb.com\/solved\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/jassweb.com\/solved\/#organization","name":"Jass Web","url":"https:\/\/jassweb.com\/solved\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/","url":"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png","contentUrl":"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png","width":693,"height":132,"caption":"Jass Web"},"image":{"@id":"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/"}},{"@type":"Person","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31","name":"Kirat","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/person\/image\/","url":"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1775798750","contentUrl":"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1775798750","caption":"Kirat"},"sameAs":["http:\/\/jassweb.com"],"url":"https:\/\/jassweb.com\/solved\/author\/jaspritsinghghumangmail-com\/"}]}},"_links":{"self":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/posts\/13604","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/comments?post=13604"}],"version-history":[{"count":0,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/posts\/13604\/revisions"}],"wp:attachment":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/media?parent=13604"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/categories?post=13604"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/tags?post=13604"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}