{"id":830,"date":"2026-10-09T13:00:00","date_gmt":"2026-10-09T07:30:00","guid":{"rendered":"https:\/\/smitabharat.com\/blog\/go-mutex-worker-pool-programs\/"},"modified":"2026-11-29T01:29:28","modified_gmt":"2026-11-28T19:59:28","slug":"go-mutex-worker-pool-programs","status":"publish","type":"post","link":"https:\/\/smitabharat.com\/blog\/go-mutex-worker-pool-programs\/","title":{"rendered":"Go Mutex Programs: Worker Pool, Atomic, RWMutex and Context"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">Go mutex programs protect shared data when many goroutines read and write it at the same time, and worker pools control how many goroutines do the work. Together with <code>context<\/code>, these are the tools you use to build safe, fast backend services. In this post, you will write fourteen programs with their exact output and the logic explained in comments, covering safe counters, caches, worker pools, timeouts and cancellation.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You should first finish our <a href=\"https:\/\/smitabharat.com\/blog\/go-goroutine-programs\/\">Go goroutine programs<\/a> and <a href=\"https:\/\/smitabharat.com\/blog\/go-channel-programs\/\">Go channel programs<\/a>. For the theory, read <a href=\"https:\/\/smitabharat.com\/blog\/go-sync-package-waitgroup-mutex\/\">WaitGroup and Mutex explained<\/a>, the <a href=\"https:\/\/smitabharat.com\/blog\/go-worker-pool-pattern\/\">Go worker pool pattern<\/a> and the <a href=\"https:\/\/smitabharat.com\/blog\/go-context-beginners-guide\/\">Go context guide<\/a>. All programs were tested on Go 1.27.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">What are Go Mutex Programs?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Go mutex programs use <code>sync.Mutex<\/code>, which is a lock. Before touching shared data, a goroutine calls <code>Lock<\/code>. When it is done, it calls <code>Unlock<\/code>. While one goroutine holds the lock, every other goroutine that calls <code>Lock<\/code> waits its turn.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Think of a single bathroom key in an office. Only the person holding the key can go in. Everyone else waits at the door until the key comes back. A mutex is that key, and the shared data is the bathroom.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Why Go Mutex Programs Matter<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">When two goroutines update the same variable at the same time, updates can be lost. This bug is called a data race, and it causes wrong totals, broken maps and random crashes. Go mutex programs and worker pools prevent these bugs and keep resource use under control.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Correct results:<\/strong> counters, balances and caches stay accurate.<\/li>\n\n\n<li><strong>Controlled load:<\/strong> a worker pool limits how many jobs run at once.<\/li>\n\n\n<li><strong>Clean shutdown:<\/strong> <code>context<\/code> tells every worker to stop on a timeout or cancel.<\/li>\n\n\n<li><strong>Interviews:<\/strong> worker pools and race fixes are among the most asked Go programs.<\/li>\n\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">How Go Mutex Programs Work<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">A data race happens because <code>count++<\/code> is really three steps: read, add, write. Two goroutines can both read 5, both add 1 and both write 6, losing one update. A mutex makes the three steps happen as one, because only one goroutine is inside the locked section at a time.<\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"640\" src=\"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-mutex-worker-pool-programs-diagram-1-1024x640.png\" alt=\"Go mutex programs diagram showing goroutines waiting for a lock before updating a shared counter\" class=\"wp-image-828\" srcset=\"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-mutex-worker-pool-programs-diagram-1-1024x640.png 1024w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-mutex-worker-pool-programs-diagram-1-300x188.png 300w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-mutex-worker-pool-programs-diagram-1-768x480.png 768w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-mutex-worker-pool-programs-diagram-1-1536x960.png 1536w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-mutex-worker-pool-programs-diagram-1-2048x1280.png 2048w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><figcaption class=\"wp-element-caption\">Only the goroutine holding the lock can update the counter, so every increment is counted.<\/figcaption><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">The table below lists the tools in this post.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Tool<\/th><th>Package<\/th><th>Use it for<\/th><\/tr><\/thead><tbody><tr><td>sync.Mutex<\/td><td>sync<\/td><td>One goroutine at a time<\/td><\/tr><tr><td>sync.RWMutex<\/td><td>sync<\/td><td>Many readers or one writer<\/td><\/tr><tr><td>atomic.Int64<\/td><td>sync\/atomic<\/td><td>Fast counters and flags<\/td><\/tr><tr><td>sync.Map<\/td><td>sync<\/td><td>Special caches with stable keys<\/td><\/tr><tr><td>Worker pool<\/td><td>channels + WaitGroup<\/td><td>Fixed number of workers<\/td><\/tr><tr><td>context.WithTimeout<\/td><td>context<\/td><td>Stop work after a time limit<\/td><\/tr><tr><td>context.WithCancel<\/td><td>context<\/td><td>Stop work on demand<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Lock-Based Go Mutex Programs<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">These first Go mutex programs fix data races with locks and atomics. Two short names appear in almost every program: <code>mu<\/code> is the mutex, and <code>wg<\/code> is the wait group.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 1: Safe Counter with a Mutex<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"\n    \"sync\"\n)\n\nfunc main() {\n    var mu sync.Mutex     \/\/ mu is the mutex (the lock)\n    var wg sync.WaitGroup \/\/ wg is a wait group: it waits for goroutines to finish\n    count := 0\n\n    for range 1000 { \/\/ repeat 1000 times\n        \/\/ wg.Go starts the function in a new goroutine and calls Done for you (Go 1.25+)\n        wg.Go(func() {\n            mu.Lock()         \/\/ wait for the key\n            defer mu.Unlock() \/\/ defer gives the key back when this function ends\n            count++           \/\/ only one goroutine runs this line at a time\n        })\n    }\n    wg.Wait() \/\/ wait until all 1000 goroutines are done\n    fmt.Println(\"count:\", count)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>count: 1000<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Here is what happens. Each of the 1000 goroutines takes the lock, adds 1 and gives the lock back. So no update is lost, and the count is always 1000. Without <code>Lock<\/code> and <code>Unlock<\/code>, the count would often be below 1000, and <code>go run -race<\/code> would report a data race. Read our <a href=\"https:\/\/smitabharat.com\/blog\/go-race-detector-data-races\/\">Go race detector guide<\/a> to see that report.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 2: The Classic Way with wg.Add and wg.Done<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"\n    \"sync\"\n)\n\n\/\/ addMoney adds amount to the shared total while holding the lock.\nfunc addMoney(total *int, amount int, mu *sync.Mutex, wg *sync.WaitGroup) {\n    defer wg.Done() \/\/ tell the wait group this goroutine is finished\n    mu.Lock()\n    *total += amount \/\/ *total means \"the int that this pointer points to\"\n    mu.Unlock()\n}\n\nfunc main() {\n    var mu sync.Mutex\n    var wg sync.WaitGroup\n    total := 0\n    amounts := []int{100, 250, 50}\n\n    for _, amount := range amounts {\n        wg.Add(1) \/\/ one more goroutine to wait for\n        go addMoney(&amp;total, amount, &amp;mu, &amp;wg) \/\/ &amp; passes a pointer, so all share the same values\n    }\n    wg.Wait()\n    fmt.Println(\"wallet total:\", total)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>wallet total: 400<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">This program does the same job as Program 1 in the older style. You call <code>wg.Add(1)<\/code> before each goroutine starts. Then each goroutine calls <code>wg.Done()<\/code> when it finishes. You will see this style in a lot of existing Go code, so it is good to know both.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 3: Atomic Counter Without a Lock<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"\n    \"sync\"\n    \"sync\/atomic\"\n)\n\nfunc main() {\n    var visits atomic.Int64 \/\/ a number that is safe to use from many goroutines\n    var wg sync.WaitGroup\n    for range 500 {\n        wg.Go(func() {\n            visits.Add(1) \/\/ one CPU instruction, no lock needed\n        })\n    }\n    wg.Wait()\n    fmt.Println(\"visits:\", visits.Load()) \/\/ Load reads the current value safely\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>visits: 500<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Each goroutine adds 1 with <code>visits.Add(1)<\/code>, and the CPU does that in one safe step. So you need no mutex at all. Atomics are faster than a mutex for a single number. For anything bigger, like a map or two related fields, use a mutex.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 4: Use defer to Unlock on Every Return<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"\n    \"sync\"\n)\n\nvar mu sync.Mutex\nvar stock = 2 \/\/ tickets left, shared by everyone\n\n\/\/ buyTicket sells one ticket if any are left.\nfunc buyTicket(name string) {\n    mu.Lock()\n    defer mu.Unlock() \/\/ runs on every return below, so we never forget it\n\n    if stock == 0 {\n        fmt.Println(name + \": sold out\") \/\/ + joins two strings\n        return \/\/ early return: defer still unlocks\n    }\n    stock--\n    fmt.Println(name + \": got a ticket\")\n}\n\nfunc main() {\n    buyTicket(\"Asha\")\n    buyTicket(\"Ravi\")\n    buyTicket(\"Meera\")\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>Asha: got a ticket\nRavi: got a ticket\nMeera: sold out<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The function has two ways out: the sold-out <code>return<\/code> and the normal end. If you wrote <code>mu.Unlock()<\/code> by hand, you would need it in both places. With <code>defer mu.Unlock()<\/code>, Go unlocks for you whichever way the function ends.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 5: A Bank Account Struct with Its Own Mutex<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"errors\"\n    \"fmt\"\n    \"sync\"\n)\n\n\/\/ Account holds a balance and the lock that protects it.\ntype Account struct {\n    mu      sync.Mutex \/\/ protects balance\n    balance int\n}\n\n\/\/ Deposit adds money to the account.\nfunc (account *Account) Deposit(amount int) {\n    account.mu.Lock()\n    defer account.mu.Unlock() \/\/ unlock even if the code below panics\n    account.balance += amount\n}\n\n\/\/ Withdraw takes money out, or returns an error if there is not enough.\nfunc (account *Account) Withdraw(amount int) error {\n    account.mu.Lock()\n    defer account.mu.Unlock()\n    if amount &gt; account.balance {\n        return errors.New(\"insufficient funds\")\n    }\n    account.balance -= amount\n    return nil \/\/ nil means \"no error\"\n}\n\n\/\/ Balance returns the current balance.\nfunc (account *Account) Balance() int {\n    account.mu.Lock()\n    defer account.mu.Unlock()\n    return account.balance\n}\n\nfunc main() {\n    myAccount := &amp;Account{balance: 1000} \/\/ &amp; gives a pointer to the new Account\n    var wg sync.WaitGroup\n    for range 100 {\n        wg.Go(func() { myAccount.Deposit(10) })\n        wg.Go(func() { myAccount.Withdraw(5) })\n    }\n    wg.Wait()\n    fmt.Println(\"final balance:\", myAccount.Balance())\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>final balance: 1500<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">100 deposits of 10 add 1000, and 100 withdrawals of 5 remove 500, so the result is always 1500. Every method locks first, so two goroutines never change <code>balance<\/code> together. Keeping the mutex inside the struct, next to the data it guards, is the normal Go style.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 6: A Read-Heavy Cache with RWMutex<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"\n    \"sync\"\n)\n\n\/\/ Cache is a map that many goroutines can read at the same time.\ntype Cache struct {\n    mu   sync.RWMutex\n    data map[string]string\n}\n\n\/\/ Get looks up a key. ok is true if the key was found.\nfunc (cache *Cache) Get(key string) (string, bool) {\n    cache.mu.RLock() \/\/ many readers can hold RLock together\n    defer cache.mu.RUnlock()\n    value, ok := cache.data[key]\n    return value, ok\n}\n\n\/\/ Set stores a value under a key.\nfunc (cache *Cache) Set(key, value string) {\n    cache.mu.Lock() \/\/ a writer waits for all readers, then blocks them\n    defer cache.mu.Unlock()\n    cache.data[key] = value\n}\n\n\/\/ allTrue reports whether every item in the slice is true.\nfunc allTrue(results []bool) bool {\n    for _, result := range results {\n        if !result {\n            return false\n        }\n    }\n    return true\n}\n\nfunc main() {\n    countries := &amp;Cache{data: map[string]string{}}\n    countries.Set(\"IN\", \"India\")\n\n    var wg sync.WaitGroup\n    hits := make([]bool, 50) \/\/ one slot per reader, so readers never share a slot\n    for i := range 50 {\n        wg.Go(func() {\n            _, hits[i] = countries.Get(\"IN\") \/\/ 50 readers at once\n        })\n    }\n    wg.Wait()\n    fmt.Println(\"all hits:\", allTrue(hits))\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>all hits: true<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">You store one country, and then 50 goroutines read it at the same time. <code>RWMutex<\/code> lets all those readers in together, which is faster for caches that are read far more often than written. A writer still gets the data alone, because <code>Lock<\/code> waits for every reader to leave.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Worker Pool Go Mutex Programs<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">A worker pool starts a fixed number of goroutines that pull jobs from one channel. It is one of the most asked Go programs in interviews, and many real Go mutex programs pair a pool with a lock or an atomic counter.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 7: A Basic Worker Pool<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"\n    \"sync\"\n)\n\n\/\/ Result is the answer for one job.\ntype Result struct {\n    Job    int\n    Square int\n}\n\n\/\/ worker takes jobs until the jobs channel is closed.\nfunc worker(jobs &lt;-chan int, results chan&lt;- Result, wg *sync.WaitGroup) {\n    defer wg.Done()\n    for job := range jobs { \/\/ keep taking jobs until the channel is closed\n        results &lt;- Result{Job: job, Square: job * job}\n    }\n}\n\nfunc main() {\n    jobs := make(chan int, 10)\n    results := make(chan Result, 10)\n    var wg sync.WaitGroup\n\n    \/\/ Step 1: start 3 workers.\n    for range 3 {\n        wg.Add(1)\n        go worker(jobs, results, &amp;wg)\n    }\n    \/\/ Step 2: send 6 jobs, then close so workers know there are no more.\n    for job := 1; job &lt;= 6; job++ {\n        jobs &lt;- job\n    }\n    close(jobs)\n    \/\/ Step 3: wait for the workers, then close results.\n    wg.Wait()\n    close(results)\n\n    \/\/ Step 4: put each answer in the slot for its job number.\n    squares := make([]int, 7)\n    for result := range results {\n        squares[result.Job] = result.Square\n    }\n    for job := 1; job &lt;= 6; job++ {\n        fmt.Printf(\"job %d -&gt; %d\\n\", job, squares[job])\n    }\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>job 1 -&gt; 1\njob 2 -&gt; 4\njob 3 -&gt; 9\njob 4 -&gt; 16\njob 5 -&gt; 25\njob 6 -&gt; 36<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Which worker takes which job changes every run. So each answer goes into the slot for its job number, and you print the slots in order. The pattern is always the same: start workers, send jobs, close jobs, wait, close results.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 8: Limit Concurrency with a Semaphore Channel<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"\n    \"sync\"\n    \"time\"\n)\n\nfunc main() {\n    slots := make(chan struct{}, 2) \/\/ a semaphore: at most 2 tasks at once\n    var mu sync.Mutex\n    var wg sync.WaitGroup\n    running := 0 \/\/ tasks working right now\n    peak := 0    \/\/ the highest value running ever reached\n\n    for range 6 {\n        wg.Go(func() {\n            slots &lt;- struct{}{}        \/\/ take a slot (waits if both are taken)\n            defer func() { &lt;-slots }() \/\/ give the slot back at the end\n\n            mu.Lock()\n            running++\n            if running &gt; peak {\n                peak = running\n            }\n            mu.Unlock()\n\n            time.Sleep(20 * time.Millisecond) \/\/ pretend to work\n\n            mu.Lock()\n            running--\n            mu.Unlock()\n        })\n    }\n    wg.Wait()\n    fmt.Println(\"max running at once:\", peak)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>max running at once: 2<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The buffered channel works like a car park with two spaces. A goroutine can only start work after it gets a space, so no more than two ever run together. The mutex protects <code>running<\/code> and <code>peak<\/code>, because six goroutines update them.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Context in Go Mutex Programs<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\"><code>context<\/code> tells goroutines when to stop, either after a timeout or when you cancel. Real Go mutex programs almost always use it, so a stuck worker never holds a lock forever. In the code, <code>ctx<\/code> is the usual short name for a context.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 9: Stop a Slow Task with WithTimeout<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"context\"\n    \"fmt\"\n    \"time\"\n)\n\n\/\/ fetchReport waits for the work or for the caller to give up.\nfunc fetchReport(ctx context.Context, delay time.Duration) (string, error) {\n    select {\n    case &lt;-time.After(delay): \/\/ the work finished\n        return \"report ready\", nil\n    case &lt;-ctx.Done(): \/\/ the caller gave up\n        return \"\", ctx.Err()\n    }\n}\n\nfunc main() {\n    delays := []time.Duration{50 * time.Millisecond, 500 * time.Millisecond}\n    for _, delay := range delays {\n        \/\/ ctx gives up after 100ms; cancel frees its timer.\n        ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)\n        report, err := fetchReport(ctx, delay) \/\/ err is the error value, nil if all went well\n        cancel() \/\/ always call cancel to free resources\n        if err != nil {\n            fmt.Println(delay, \"-&gt;\", err) \/\/ timed out: print only the reason\n            continue\n        }\n        fmt.Println(delay, \"-&gt;\", report, err)\n    }\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>50ms -&gt; report ready &lt;nil&gt;\n500ms -&gt; context deadline exceeded<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The 50ms task finishes before the 100ms limit, so you get the report. The 500ms task is too slow. When the deadline passes, <code>ctx.Done()<\/code> closes and <code>ctx.Err()<\/code> explains why. The <code>cancel()<\/code> call frees the timer behind the context.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 10: Cancel All Workers on Demand<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"context\"\n    \"fmt\"\n    \"sync\"\n    \"sync\/atomic\"\n    \"time\"\n)\n\nfunc main() {\n    ctx, cancel := context.WithCancel(context.Background())\n    var processed atomic.Int64\n    var wg sync.WaitGroup\n\n    for range 3 {\n        wg.Go(func() {\n            for { \/\/ loop until told to stop\n                select {\n                case &lt;-ctx.Done(): \/\/ stop signal for every worker\n                    return\n                default: \/\/ no stop signal yet, so do one piece of work\n                    processed.Add(1)\n                    time.Sleep(10 * time.Millisecond)\n                }\n            }\n        })\n    }\n\n    time.Sleep(55 * time.Millisecond)\n    cancel()  \/\/ tell all workers to stop\n    wg.Wait() \/\/ wait until they really have stopped\n    fmt.Println(\"stopped cleanly, some work done:\", processed.Load() &gt; 0)\n    fmt.Println(\"reason:\", ctx.Err())\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>stopped cleanly, some work done: true\nreason: context canceled<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Three workers keep doing small pieces of work. After 55ms, one <code>cancel<\/code> call closes <code>ctx.Done()<\/code> for all of them, so each worker returns. This is how servers shut down workers during a deploy.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 11: sync.Map for a Shared Registry<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"\n    \"sync\"\n)\n\nfunc main() {\n    var sessions sync.Map \/\/ safe for concurrent use without your own mutex\n    var wg sync.WaitGroup\n    for _, user := range []string{\"asha\", \"ravi\", \"meera\"} {\n        wg.Go(func() {\n            sessions.Store(user, \"logged-in\")\n        })\n    }\n    wg.Wait()\n\n    status, ok := sessions.Load(\"ravi\") \/\/ ok is true if the key was found\n    fmt.Println(status, ok)\n\n    \/\/ Range calls the function once for every key and value.\n    count := 0\n    sessions.Range(func(key, value any) bool {\n        count++\n        return true \/\/ true means \"keep going\"\n    })\n    fmt.Println(\"sessions:\", count)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>logged-in true\nsessions: 3<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Three goroutines store a session each, with no mutex of your own. Then <code>Load<\/code> reads one key, and <code>Range<\/code> counts all of them. <code>sync.Map<\/code> is built for keys that are written once and read many times. For most other cases, a normal map with a mutex is simpler and just as fast.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Most Asked Interview Go Mutex Programs<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Program 12: Fix the Classic Race in a Map<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"\n    \"sync\"\n)\n\n\/\/ Counter counts page visits safely.\ntype Counter struct {\n    mu   sync.Mutex\n    hits map[string]int\n}\n\n\/\/ Inc adds one visit for the given page.\nfunc (counter *Counter) Inc(page string) {\n    counter.mu.Lock()\n    counter.hits[page]++ \/\/ map writes from many goroutines MUST be locked\n    counter.mu.Unlock()\n}\n\nfunc main() {\n    visits := Counter{hits: map[string]int{}}\n    var wg sync.WaitGroup\n    pages := []string{\"\/home\", \"\/blog\", \"\/home\"}\n    for range 100 {\n        for _, page := range pages {\n            wg.Go(func() { visits.Inc(page) })\n        }\n    }\n    wg.Wait()\n    fmt.Println(visits.hits[\"\/home\"], visits.hits[\"\/blog\"])\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>200 100<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Each round visits <code>\/home<\/code> twice and <code>\/blog<\/code> once, and there are 100 rounds. So the counts are 200 and 100. Without the mutex, Go may crash with &#8220;fatal error: concurrent map writes&#8221;. Plain maps are never safe for concurrent writes.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 13: Worker Pool That Stops on the First Error<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"context\"\n    \"fmt\"\n    \"sync\"\n)\n\nfunc main() {\n    ctx, cancel := context.WithCancel(context.Background())\n    defer cancel()\n    jobs := make(chan int)\n    var once sync.Once \/\/ once.Do runs its function only one time\n    var firstErr error\n    var wg sync.WaitGroup\n\n    \/\/ Step 1: start 3 workers.\n    for range 3 {\n        wg.Go(func() {\n            for job := range jobs {\n                if job == 4 { \/\/ pretend job 4 fails\n                    once.Do(func() {\n                        firstErr = fmt.Errorf(\"job %d: bad input\", job)\n                        cancel() \/\/ stop the producer and other workers\n                    })\n                    return\n                }\n            }\n        })\n    }\n\n    \/\/ Step 2: send jobs, but stop as soon as the context is cancelled.\n    for job := 1; job &lt;= 10; job++ {\n        if ctx.Err() != nil { \/\/ not nil means cancel was called\n            break\n        }\n        select {\n        case jobs &lt;- job: \/\/ a worker took the job\n        case &lt;-ctx.Done(): \/\/ cancelled while waiting\n        }\n    }\n\n    \/\/ Step 3: close jobs, wait for the workers and print the error.\n    close(jobs)\n    wg.Wait()\n    fmt.Println(\"error:\", firstErr)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>error: job 4: bad input<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">When a worker gets job 4, it saves the error and calls <code>cancel<\/code>. <code>sync.Once<\/code> keeps only the first error, even if many workers fail. The producer sees the cancel and stops sending. The <code>golang.org\/x\/sync\/errgroup<\/code> package wraps this whole pattern into a few lines.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 14: Avoid Deadlock with Lock Ordering<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"\n    \"sync\"\n)\n\n\/\/ Wallet has an ID, a balance and its own lock.\ntype Wallet struct {\n    ID      int\n    mu      sync.Mutex\n    Balance int\n}\n\n\/\/ transfer always locks the wallet with the smaller ID first.\n\/\/ If two transfers lock in opposite orders, they can deadlock.\nfunc transfer(from, to *Wallet, amount int) {\n    \/\/ Step 1: decide the lock order.\n    first := from\n    second := to\n    if to.ID &lt; from.ID {\n        first = to\n        second = from\n    }\n    \/\/ Step 2: lock both wallets in that order.\n    first.mu.Lock()\n    defer first.mu.Unlock()\n    second.mu.Lock()\n    defer second.mu.Unlock()\n    \/\/ Step 3: move the money.\n    from.Balance -= amount\n    to.Balance += amount\n}\n\nfunc main() {\n    walletOne := &amp;Wallet{ID: 1, Balance: 500}\n    walletTwo := &amp;Wallet{ID: 2, Balance: 500}\n    var wg sync.WaitGroup\n    for range 50 {\n        wg.Go(func() { transfer(walletOne, walletTwo, 3) })\n        wg.Go(func() { transfer(walletTwo, walletOne, 2) })\n    }\n    wg.Wait()\n    total := walletOne.Balance + walletTwo.Balance\n    fmt.Println(walletOne.Balance, walletTwo.Balance, total)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>450 550 1000<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Both directions lock wallet 1 before wallet 2, so two transfers can never wait on each other in a circle. Wallet 1 sends 3 fifty times and gets 2 back fifty times, so it ends at 450. The total money always stays 1000.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Mutex vs Channels in Go Mutex Programs<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Both tools make concurrent code safe. Go mutex programs share memory under a lock, while channel programs pass data between goroutines. The diagram and table below compare them.<\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"640\" src=\"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-mutex-worker-pool-programs-diagram-2-1024x640.png\" alt=\"Go mutex programs comparison of mutexes and channels\" class=\"wp-image-829\" srcset=\"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-mutex-worker-pool-programs-diagram-2-1024x640.png 1024w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-mutex-worker-pool-programs-diagram-2-300x188.png 300w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-mutex-worker-pool-programs-diagram-2-768x480.png 768w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-mutex-worker-pool-programs-diagram-2-1536x960.png 1536w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-mutex-worker-pool-programs-diagram-2-2048x1280.png 2048w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><figcaption class=\"wp-element-caption\">Use a mutex to guard shared state, and channels to pass work and signals between goroutines.<\/figcaption><\/figure>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Feature<\/th><th>Mutex<\/th><th>Channel<\/th><\/tr><\/thead><tbody><tr><td>Best for<\/td><td>Guarding shared state<\/td><td>Passing data and signals<\/td><\/tr><tr><td>Example<\/td><td>Counter, cache, balance<\/td><td>Job queue, results, stop signal<\/td><\/tr><tr><td>Ownership<\/td><td>Shared by many<\/td><td>Moves from sender to receiver<\/td><\/tr><tr><td>Risk<\/td><td>Forgetting Unlock, deadlocks<\/td><td>Deadlocks, leaks, closed channel panics<\/td><\/tr><tr><td>Speed for a counter<\/td><td>Fast<\/td><td>Slower<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">A simple rule helps: if goroutines share a value, use a mutex. If they hand work to each other, use a channel.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Common Mistakes in Go Mutex Programs<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Forgetting Unlock:<\/strong> every other goroutine then waits forever, so use <code>defer mu.Unlock()<\/code>.<\/li>\n\n\n<li><strong>Locking twice in one goroutine:<\/strong> Go mutexes are not re-entrant, so a second <code>Lock<\/code> deadlocks.<\/li>\n\n\n<li><strong>Copying a struct with a mutex:<\/strong> the copy has its own lock, so use pointer receivers.<\/li>\n\n\n<li><strong>Forgetting cancel():<\/strong> a context without <code>cancel<\/code> leaks a timer until it expires.<\/li>\n\n\n<li><strong>Closing the jobs channel from a worker:<\/strong> only the producer should close it.<\/li>\n\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Best Practices for Go Mutex Programs<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Keep the locked section small<\/strong>, only around the shared data.<\/li>\n\n\n<li><strong>Put the mutex next to the data<\/strong> it protects, inside the same struct.<\/li>\n\n\n<li><strong>Use atomics for single counters<\/strong> and a mutex for anything larger.<\/li>\n\n\n<li><strong>Pass context.Context as the first argument<\/strong> of functions that may be slow.<\/li>\n\n\n<li><strong>Run tests with -race<\/strong> to catch the races you missed.<\/li>\n\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Go Mutex Programs Interview Questions and Answers<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">These are the concurrency safety questions interviewers ask most, and they build on the Go mutex programs above. Each program is complete, with real output from Go 1.27.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mutex Questions<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q1. What happens if you lock a mutex twice in the same goroutine?<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"sync\"\n\nfunc main() {\n    var mu sync.Mutex\n    mu.Lock()\n    mu.Lock() \/\/ waits for itself forever\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>fatal error: all goroutines are asleep - deadlock!<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Go mutexes are not re-entrant. A function that holds a lock must not call another function that takes the same lock.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q2. What is the difference between Mutex and RWMutex?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>Mutex<\/code> lets one goroutine in at a time. <code>RWMutex<\/code> lets many readers in together with <code>RLock<\/code>, but a writer with <code>Lock<\/code> gets the data alone. Use <code>RWMutex<\/code> only when reads greatly outnumber writes.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q3. Why should a struct with a mutex use pointer receivers?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A value receiver copies the struct, including the mutex. Each copy has its own lock, so the lock no longer protects the shared data. <code>go vet<\/code> warns about this.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Atomic and Context Questions<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q4. When should you use sync\/atomic instead of a mutex?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For single values like counters and flags, atomics are faster and simpler. When several fields must change together, such as a balance and a history list, use a mutex.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q5. What does this program print?<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"context\"\n    \"fmt\"\n    \"time\"\n)\n\nfunc main() {\n    \/\/ Case 1: cancel before the time limit.\n    longCtx, cancelLong := context.WithTimeout(context.Background(), time.Hour)\n    cancelLong()\n    &lt;-longCtx.Done() \/\/ already closed, so this does not wait\n    fmt.Println(longCtx.Err())\n\n    \/\/ Case 2: let the time limit run out.\n    shortCtx, cancelShort := context.WithTimeout(context.Background(), 10*time.Millisecond)\n    defer cancelShort()\n    &lt;-shortCtx.Done() \/\/ waits about 10ms\n    fmt.Println(shortCtx.Err())\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>context canceled\ncontext deadline exceeded<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Calling <code>cancel<\/code> early gives &#8220;context canceled&#8221;. Letting the time run out gives &#8220;context deadline exceeded&#8221;. Code can check which one happened with <code>errors.Is<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q6. What does this program print?<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"\n    \"sync\/atomic\"\n)\n\nfunc main() {\n    var ready atomic.Bool \/\/ starts as false\n    fmt.Println(ready.Load())\n    ready.Store(true)\n\n    \/\/ CompareAndSwap(old, new): if the value is old, set it to new.\n    swapped := ready.CompareAndSwap(true, false)\n    fmt.Println(swapped, ready.Load())\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>false\ntrue false<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The flag starts as false. After <code>Store(true)<\/code>, it equals the old value <code>true<\/code>, so <code>CompareAndSwap<\/code> changes it to false and returns true. It is the building block of many lock-free tricks.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Worker Pool Questions in Go Mutex Programs<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q7. How many workers should a pool have?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For CPU-heavy work, start with <code>runtime.NumCPU()<\/code> workers. For work that waits on the network or disk, you can use more, then measure and adjust.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q8. Why close the jobs channel?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Closing tells every worker&#8217;s <code>for range jobs<\/code> loop to stop after the last job. Without it, workers wait forever and <code>wg.Wait()<\/code> never returns.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q9. Why do worker pool results come back in random order?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Workers run at the same time and finish at different speeds. If order matters, attach the job index to each result and sort, or write each result into its own slot.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q10. What does this program print?<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"\n    \"sync\"\n)\n\nfunc main() {\n    jobs := make(chan int, 5)\n    var mu sync.Mutex\n    var wg sync.WaitGroup\n    total := 0\n    for range 2 { \/\/ two workers share one total\n        wg.Go(func() {\n            for job := range jobs {\n                mu.Lock()\n                total += job\n                mu.Unlock()\n            }\n        })\n    }\n    for job := 1; job &lt;= 5; job++ {\n        jobs &lt;- job\n    }\n    close(jobs)\n    wg.Wait()\n    fmt.Println(total)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>15<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Two workers add jobs 1 to 5 into one total. The mutex makes sure no addition is lost, so the answer is always 15.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q11. What is a deadlock, and how do you avoid one?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A deadlock is when goroutines wait on each other forever, for example A holds lock 1 and waits for lock 2 while B holds lock 2 and waits for lock 1. Avoid it by always taking locks in the same order, as in Program 14, and by holding locks for as short a time as possible.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q12. What does go run -race do?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It builds the program with a race detector that watches every memory access. If two goroutines touch the same memory without sync and one of them writes, it prints a report with both stack traces.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Practice Task<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">To practise Go mutex programs, build an image resize simulator: a worker pool of 3 workers processes 10 &#8220;images&#8221;, each taking a fake 30 ms, with a total time limit of 200 ms using <code>context.WithTimeout<\/code>. Print how many images finished before the deadline. Hint: count finished jobs with an <code>atomic.Int64<\/code> and check <code>ctx.Done()<\/code> inside the worker loop.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Official Resources<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/pkg.go.dev\/sync\">sync package documentation<\/a><\/li>\n\n\n<li><a href=\"https:\/\/pkg.go.dev\/sync\/atomic\">sync\/atomic package documentation<\/a><\/li>\n\n\n<li><a href=\"https:\/\/pkg.go.dev\/context\">context package documentation<\/a><\/li>\n\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Quick Recap<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Go mutex programs use <code>Lock<\/code> and <code>Unlock<\/code> so only one goroutine changes shared data at a time.<\/li>\n\n\n<li><code>RWMutex<\/code> allows many readers, and atomics are best for single counters.<\/li>\n\n\n<li>A worker pool starts a fixed number of workers that pull jobs from a channel.<\/li>\n\n\n<li><code>context.WithTimeout<\/code> and <code>WithCancel<\/code> tell every worker when to stop.<\/li>\n\n\n<li>Avoid deadlocks by locking in a fixed order and never locking twice in one goroutine.<\/li>\n\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">What&#8217;s Next?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Next, we write code that works for many types at once. Read <a href=\"https:\/\/smitabharat.com\/blog\/go-generics-programs\/\">Go generics programs with output<\/a>, with Map, Filter, Reduce and a generic stack. For more practice, see the <a href=\"https:\/\/smitabharat.com\/blog\/go-sync-package-questions-part-16\/\">Go sync package interview questions<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Go mutex programs protect shared data when many goroutines read and write it at the same time, and worker pools control how many goroutines&hellip;<\/p>\n","protected":false},"author":1,"featured_media":827,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_swapz_level":"","_swapz_series_part":0,"_swapz_hide_toc":false,"_swapz_hide_featured":false,"_swapz_description":"","footnotes":""},"categories":[106],"tags":[96,79,95,11,104],"swapz_series":[],"class_list":["post-830","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-go-programs","tag-beginner","tag-go-concurrency","tag-go-interview-questions","tag-go-lang","tag-go-programs"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v28.9 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Go Mutex Programs: Worker Pool, Atomic, Context<\/title>\n<meta name=\"description\" content=\"Go mutex programs with output: safe counters, atomics, RWMutex cache, worker pools, semaphores, context timeouts and deadlock fixes, plus interview Q&amp;A.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/smitabharat.com\/blog\/go-mutex-worker-pool-programs\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Go Mutex Programs: Worker Pool, Atomic, Context\" \/>\n<meta property=\"og:description\" content=\"Go mutex programs with output: safe counters, atomics, RWMutex cache, worker pools, semaphores, context timeouts and deadlock fixes, plus interview Q&amp;A.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/smitabharat.com\/blog\/go-mutex-worker-pool-programs\/\" \/>\n<meta property=\"og:site_name\" content=\"Smita Bharat - Blog\" \/>\n<meta property=\"article:published_time\" content=\"2026-10-09T07:30:00+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2026-11-28T19:59:28+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-mutex-worker-pool-programs-featured.png\" \/>\n\t<meta property=\"og:image:width\" content=\"2400\" \/>\n\t<meta property=\"og:image:height\" content=\"1260\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"Smita\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Smita\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"20 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-mutex-worker-pool-programs\\\/#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-mutex-worker-pool-programs\\\/\"},\"author\":{\"name\":\"Smita\",\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#\\\/schema\\\/person\\\/27a1b1067d396703215c54acedbfd339\"},\"headline\":\"Go Mutex Programs: Worker Pool, Atomic, RWMutex and Context\",\"datePublished\":\"2026-10-09T07:30:00+00:00\",\"dateModified\":\"2026-11-28T19:59:28+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-mutex-worker-pool-programs\\\/\"},\"wordCount\":2124,\"publisher\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#\\\/schema\\\/person\\\/27a1b1067d396703215c54acedbfd339\"},\"image\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-mutex-worker-pool-programs\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/wp-content\\\/uploads\\\/2026\\\/10\\\/go-mutex-worker-pool-programs-featured.png\",\"keywords\":[\"Beginner\",\"Go Concurrency\",\"Go Interview Questions\",\"Go Lang\",\"Go Programs\"],\"articleSection\":[\"Go Programs\"],\"inLanguage\":\"en-US\"},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-mutex-worker-pool-programs\\\/\",\"url\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-mutex-worker-pool-programs\\\/\",\"name\":\"Go Mutex Programs: Worker Pool, Atomic, Context\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-mutex-worker-pool-programs\\\/#primaryimage\"},\"image\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-mutex-worker-pool-programs\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/wp-content\\\/uploads\\\/2026\\\/10\\\/go-mutex-worker-pool-programs-featured.png\",\"datePublished\":\"2026-10-09T07:30:00+00:00\",\"dateModified\":\"2026-11-28T19:59:28+00:00\",\"description\":\"Go mutex programs with output: safe counters, atomics, RWMutex cache, worker pools, semaphores, context timeouts and deadlock fixes, plus interview Q&A.\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-mutex-worker-pool-programs\\\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-mutex-worker-pool-programs\\\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-mutex-worker-pool-programs\\\/#primaryimage\",\"url\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/wp-content\\\/uploads\\\/2026\\\/10\\\/go-mutex-worker-pool-programs-featured.png\",\"contentUrl\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/wp-content\\\/uploads\\\/2026\\\/10\\\/go-mutex-worker-pool-programs-featured.png\",\"width\":2400,\"height\":1260,\"caption\":\"Go Mutex Programs featured image: safe counter and worker pool output\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-mutex-worker-pool-programs\\\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Go Mutex Programs: Worker Pool, Atomic, RWMutex and Context\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#website\",\"url\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/\",\"name\":\"Smita Bharat Blog\",\"description\":\"Golang &amp; Backend Development Tutorials and Interview Questions\",\"publisher\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#\\\/schema\\\/person\\\/27a1b1067d396703215c54acedbfd339\"},\"alternateName\":\"Smita Bharat\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":[\"Person\",\"Organization\"],\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#\\\/schema\\\/person\\\/27a1b1067d396703215c54acedbfd339\",\"name\":\"Smita\",\"logo\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#\\\/schema\\\/person\\\/image\\\/\"},\"sameAs\":[\"https:\\\/\\\/smitabharat.com\\\/blog\"]}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Go Mutex Programs: Worker Pool, Atomic, Context","description":"Go mutex programs with output: safe counters, atomics, RWMutex cache, worker pools, semaphores, context timeouts and deadlock fixes, plus interview Q&A.","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:\/\/smitabharat.com\/blog\/go-mutex-worker-pool-programs\/","og_locale":"en_US","og_type":"article","og_title":"Go Mutex Programs: Worker Pool, Atomic, Context","og_description":"Go mutex programs with output: safe counters, atomics, RWMutex cache, worker pools, semaphores, context timeouts and deadlock fixes, plus interview Q&A.","og_url":"https:\/\/smitabharat.com\/blog\/go-mutex-worker-pool-programs\/","og_site_name":"Smita Bharat - Blog","article_published_time":"2026-10-09T07:30:00+00:00","article_modified_time":"2026-11-28T19:59:28+00:00","og_image":[{"width":2400,"height":1260,"url":"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-mutex-worker-pool-programs-featured.png","type":"image\/png"}],"author":"Smita","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Smita","Est. reading time":"20 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/smitabharat.com\/blog\/go-mutex-worker-pool-programs\/#article","isPartOf":{"@id":"https:\/\/smitabharat.com\/blog\/go-mutex-worker-pool-programs\/"},"author":{"name":"Smita","@id":"https:\/\/smitabharat.com\/blog\/#\/schema\/person\/27a1b1067d396703215c54acedbfd339"},"headline":"Go Mutex Programs: Worker Pool, Atomic, RWMutex and Context","datePublished":"2026-10-09T07:30:00+00:00","dateModified":"2026-11-28T19:59:28+00:00","mainEntityOfPage":{"@id":"https:\/\/smitabharat.com\/blog\/go-mutex-worker-pool-programs\/"},"wordCount":2124,"publisher":{"@id":"https:\/\/smitabharat.com\/blog\/#\/schema\/person\/27a1b1067d396703215c54acedbfd339"},"image":{"@id":"https:\/\/smitabharat.com\/blog\/go-mutex-worker-pool-programs\/#primaryimage"},"thumbnailUrl":"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-mutex-worker-pool-programs-featured.png","keywords":["Beginner","Go Concurrency","Go Interview Questions","Go Lang","Go Programs"],"articleSection":["Go Programs"],"inLanguage":"en-US"},{"@type":"WebPage","@id":"https:\/\/smitabharat.com\/blog\/go-mutex-worker-pool-programs\/","url":"https:\/\/smitabharat.com\/blog\/go-mutex-worker-pool-programs\/","name":"Go Mutex Programs: Worker Pool, Atomic, Context","isPartOf":{"@id":"https:\/\/smitabharat.com\/blog\/#website"},"primaryImageOfPage":{"@id":"https:\/\/smitabharat.com\/blog\/go-mutex-worker-pool-programs\/#primaryimage"},"image":{"@id":"https:\/\/smitabharat.com\/blog\/go-mutex-worker-pool-programs\/#primaryimage"},"thumbnailUrl":"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-mutex-worker-pool-programs-featured.png","datePublished":"2026-10-09T07:30:00+00:00","dateModified":"2026-11-28T19:59:28+00:00","description":"Go mutex programs with output: safe counters, atomics, RWMutex cache, worker pools, semaphores, context timeouts and deadlock fixes, plus interview Q&A.","breadcrumb":{"@id":"https:\/\/smitabharat.com\/blog\/go-mutex-worker-pool-programs\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/smitabharat.com\/blog\/go-mutex-worker-pool-programs\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/smitabharat.com\/blog\/go-mutex-worker-pool-programs\/#primaryimage","url":"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-mutex-worker-pool-programs-featured.png","contentUrl":"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-mutex-worker-pool-programs-featured.png","width":2400,"height":1260,"caption":"Go Mutex Programs featured image: safe counter and worker pool output"},{"@type":"BreadcrumbList","@id":"https:\/\/smitabharat.com\/blog\/go-mutex-worker-pool-programs\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/smitabharat.com\/blog\/"},{"@type":"ListItem","position":2,"name":"Go Mutex Programs: Worker Pool, Atomic, RWMutex and Context"}]},{"@type":"WebSite","@id":"https:\/\/smitabharat.com\/blog\/#website","url":"https:\/\/smitabharat.com\/blog\/","name":"Smita Bharat Blog","description":"Golang &amp; Backend Development Tutorials and Interview Questions","publisher":{"@id":"https:\/\/smitabharat.com\/blog\/#\/schema\/person\/27a1b1067d396703215c54acedbfd339"},"alternateName":"Smita Bharat","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/smitabharat.com\/blog\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":["Person","Organization"],"@id":"https:\/\/smitabharat.com\/blog\/#\/schema\/person\/27a1b1067d396703215c54acedbfd339","name":"Smita","logo":{"@id":"https:\/\/smitabharat.com\/blog\/#\/schema\/person\/image\/"},"sameAs":["https:\/\/smitabharat.com\/blog"]}]}},"_links":{"self":[{"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/posts\/830","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/comments?post=830"}],"version-history":[{"count":1,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/posts\/830\/revisions"}],"predecessor-version":[{"id":896,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/posts\/830\/revisions\/896"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/media\/827"}],"wp:attachment":[{"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/media?parent=830"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/categories?post=830"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/tags?post=830"},{"taxonomy":"swapz_series","embeddable":true,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/swapz_series?post=830"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}