Go
Unlock of Unlocked Mutex Panic Fix
An Unlock with no matching Lock held is not a recoverable panic - it is a fatal error that ends the program where it stands. This guide shows both ways the pairing breaks, why recover cannot help, and the two shapes that keep every Unlock answered by a Lock.
Written November 28, 2026 · Tested with Go 1.26.4 · 17 min read
- The rule underneath: state, not ownership
- The first failure: a mutex that was never locked
- The second failure: releasing twice
- Why recover cannot help: a fatal error is not a panic
Written November 28, 2026
Tested with Go 1.26.4
What this guide is
The crash line is fatal error: sync: unlock of unlocked mutex. It is usually searched for as a panic, and the title of this guide keeps that word, but the runtime's own label is the accurate one: this is a fatal error, not a panic, and the difference decides what you can do about it. A panic unwinds the goroutine, runs deferred functions, and can be stopped by recover. This error does none of that. The program ends at that call, deferred functions never run, and there is nothing to recover - the only fix is to never make the call.
The rule it enforces is one sentence from the sync package documentation: that call releases the mutex, and it is a run-time error if the mutex is not locked on entry to it. Every release call must answer a Lock that is still held at the moment of the call. This guide reproduces the two ways that pairing breaks - a release call on a mutex that was never locked, and a second release call after a correct pair has already closed - then proves the fatal-error point with a deferred recover that never executes, and gives the two fixes: defer the release call immediately after the Lock, and structure cleanup so the release exists only on the path that took the lock. A last section covers the RWMutex versions, which carry their own messages.
Each program below is a single file in one module - run go mod init once in an empty directory, save each program under the file name shown, and build it by that name. The transcripts of the failing programs set GOTRACEBACK=none, which suppresses the goroutine stack trace so the fatal line stands alone; a plain run prints the same lines followed by the trace, which the text describes where it matters.
The rule underneath: state, not ownership
A Mutex has exactly two states that matter here. The documentation states that the zero value for a Mutex is a mutex that is not locked, and Lock moves it to locked. The release call is only defined on the locked state. There is no count and no queue of pending releases: a release that arrives while the mutex is not locked is not early, late, or redundant - it is the error, immediately.
One thing the rule is not about is which goroutine calls what. The documentation says a locked Mutex is not associated with a particular goroutine, and that one goroutine may lock a mutex and arrange for another goroutine to release it. That program is shown near the end of this guide, and it runs cleanly. So when this fatal error fires, do not hunt for a goroutine mismatch. Hunt for a count mismatch: somewhere, the releases outnumber the locks currently held - a Lock that never ran, a release call that ran twice, or a release on a cleanup path that also runs after the normal one.
The first failure: a mutex that was never locked
The smallest form needs no locking at all. A fresh mutex is already not locked, so a single release call is already one too many:
package main
import (
"fmt"
"sync"
)
func main() {
var mu sync.Mutex
fmt.Println("about to unlock a mutex that was never locked")
mu.Unlock()
fmt.Println("after the unlock")
}
$ go build -trimpath -o p1.bin p1_never_locked.go
$ GOTRACEBACK=none ./p1.bin; echo "exit status $?"
about to unlock a mutex that was never locked
fatal error: sync: unlock of unlocked mutex
exit status 2
The line after that call never prints, and the exit status is 2. Run without GOTRACEBACK=none, the same program prints a goroutine stack trace after the fatal line: its first frames name the runtime's fatal path and the mutex's slow path for that call, and the last frame is main.main at the release line of the program - the trace points at the call that had no lock to answer, which is the only place it can point. Two hexadecimal addresses inside that trace change from run to run; everything else in it is stable.
In real code this shape is rarely a bare release call under a declaration. It is a release whose lock lives somewhere else and did not happen: a setup branch that registers the cleanup but skips the acquisition, an early return taken before the Lock, a Close or Release method called on a value whose constructor failed halfway. Whatever the surrounding code intended, at the moment of the call the mutex was not locked, and that is the whole diagnosis.
The second failure: releasing twice
The more common shape starts out correct. The lock is taken, the lock is released - and then a second release arrives, from a deferred call plus an explicit one, a success path plus a cleanup path, or two layers of code that both believe the release is theirs:
package main
import (
"fmt"
"sync"
)
func main() {
var mu sync.Mutex
mu.Lock()
fmt.Println("locked")
mu.Unlock()
fmt.Println("unlocked once")
mu.Unlock()
fmt.Println("after the second unlock")
}
$ go build -trimpath -o p2.bin p2_double_unlock.go
$ GOTRACEBACK=none ./p2.bin; echo "exit status $?"
locked
unlocked once
fatal error: sync: unlock of unlocked mutex
exit status 2
Read it as accounting. The first release is legal and does its full job: after it prints its 'once' line, the mutex is in exactly the state of the fresh mutex in the first program. The second release is therefore the same call as the first failure, one line later in the program's life. There is no memory of the earlier pair to appeal to - a mutex does not know it was locked once, only whether it is locked now. When you meet this error in a log, the second release is where it surfaced; the bug is that two places in the code each took responsibility for one release.
Why recover cannot help: a fatal error is not a panic
Because the crash is abrupt, the first instinct is often defensive: wrap the suspect code in a deferred recover and carry on. That cannot work here, and the reason is worth seeing rather than assuming. recover is documented in the builtin package as managing the behavior of a panicking goroutine - it stops a panicking sequence. A fatal error never starts one. This program sets up the strongest version of the defense - a deferred function that recovers and also prints a marker line of its own, so its execution would be visible either way:
package main
import (
"fmt"
"sync"
)
func main() {
defer func() {
if r := recover(); r != nil {
fmt.Println("recovered:", r)
}
fmt.Println("the deferred function ran")
}()
var mu sync.Mutex
fmt.Println("about to unlock an unlocked mutex")
mu.Unlock()
fmt.Println("survived the unlock")
}
$ go build -trimpath -o p3.bin p3_recover.go
$ GOTRACEBACK=none ./p3.bin; echo "exit status $?"
about to unlock an unlocked mutex
fatal error: sync: unlock of unlocked mutex
exit status 2
None of the rescue lines appear. There is no recovered: line, because there was no panic value to recover. There is no the deferred function ran line either - the deferred function itself never executed. And the survival line never appears either. The runtime raised a fatal error, printed it, and terminated the program without unwinding the goroutine at all. A recover placed anywhere - in the same function, in a caller, in a wrapper around the whole operation - observes exactly the same nothing, because the mechanism it hooks into was never engaged.
The contrast makes the boundary precise. The same deferred-recover shape wrapped around a genuine panic works exactly as documented:
package main
import "fmt"
func main() {
defer func() {
if r := recover(); r != nil {
fmt.Println("recovered:", r)
}
}()
panic("boom")
}
$ go build -trimpath -o p4.bin p4_panic_contrast.go
$ ./p4.bin; echo "exit status $?"
recovered: boom
exit status 0
Same recover call in a deferred function - opposite outcome. The difference is entirely in what the runtime was asked to do: panic starts a panicking sequence that recover can stop, while the mutex check raises a fatal error that bypasses the sequence altogether. Two practical consequences follow. First, no defensive wrapper can make an unmatched release safe; if the pairing might be wrong, the pairing is what has to change, which is what the fixes below do. Second, do not read the word "panic" in a search result or a title as a classification - the first word of the crash line is. Lines that begin panic: unwind and can be recovered; lines that begin fatal error: cannot.
First fix: defer the release right after the lock
Most double releases are born when the Lock and its release sit far apart - the lock at the top of a function, the release written by hand at each return point, or in a cleanup method some distance away. Every edit that adds a return path, an early exit, or a second cleanup call is a chance for the two sides to drift. The fix removes the distance: that release is deferred in the statement immediately after the Lock, so the pair is written once, in one place, and the deferred call runs exactly once when the function returns, by whichever path it returns:
package main
import (
"fmt"
"sync"
)
type counter struct {
mu sync.Mutex
value int
}
func (c *counter) increment() {
c.mu.Lock()
defer c.mu.Unlock()
c.value++
}
func main() {
var c counter
c.increment()
c.increment()
fmt.Println("count:", c.value)
fmt.Println("both increments completed")
}
$ go build -trimpath -o p5.bin p5_defer_fix.go
$ ./p5.bin; echo "exit status $?"
count: 2
both increments completed
exit status 0
Each increment call locks, registers its one release, works, and releases on return - twice in a row, with the counter reaching 2 and the mutex back to not locked and reusable between the calls. There is no second release anywhere in the program for an editor to duplicate, and no path through increment - present or future - that returns without the deferred release or with two of them. This is the default shape for a mutex held across a function body, and it is the first thing to reach for when this fatal error appears: find the stray release, and check whether its lock's function is deferring its own release already, or not deferring at all and relying on hand-placed calls that have drifted.
Second fix: release only on the path that locked
The defer pattern needs the lock and the release to live in one function. Some designs cannot have that: the lock is taken in an open-style method and released in a close-style one, and the close can legitimately be requested twice - once by the owner finishing, once by a deferred cleanup, once by a shutdown path. There, the repair is to make the release conditional on the state it requires: track whether the lock is held, and let the release path act only when it is. The unmatched call becomes a no-op instead of a fatal error:
package main
import (
"fmt"
"sync"
)
type session struct {
mu sync.Mutex
held bool
}
func (s *session) open() {
s.mu.Lock()
s.held = true
fmt.Println("session open")
}
func (s *session) close() {
if !s.held {
fmt.Println("close skipped: the lock is not held")
return
}
s.mu.Unlock()
s.held = false
fmt.Println("session closed")
}
func main() {
var s session
s.open()
s.close()
s.close()
fmt.Println("program still running")
}
$ go build -trimpath -o p6.bin p6_guard_fix.go
$ ./p6.bin; echo "exit status $?"
session open
session closed
close skipped: the lock is not held
program still running
exit status 0
The second close call - the exact call that was fatal in the second failure - now prints its skip line and returns. Two disciplines keep this pattern honest rather than lucky. First, the flag and the mutex are two halves of one fact, so they are only ever changed together, in the two methods that own the lifecycle: held is set where the lock is taken and cleared where it is released, nowhere else. Second, the flag is part of the owner's own state: this shape fits code where one owner drives the open/close lifecycle, as here. If several goroutines can call the release path concurrently, the check itself needs synchronization of its own, and the better fix is usually to give the release a single owner or a sync.Once - the guard is for sequential lifecycle code, not a license to make that call speculatively from anywhere. Where the caller is your own straight-line code and a doubled release is a plain logic bug, prefer the first fix and correct the call sites; a guard that absorbs a bug silently can hide it.
Releasing from a different goroutine is legal
One suspected cause can be crossed off the list. Because the documentation states that a locked mutex is not associated with a particular goroutine, this program - lock in main, release in a goroutine main starts - is correct, and it is sometimes the right shape, for example when a worker signals completion by releasing a lock its launcher took:
package main
import (
"fmt"
"sync"
)
func main() {
var mu sync.Mutex
done := make(chan struct{})
mu.Lock()
go func() {
mu.Unlock()
close(done)
}()
<-done
fmt.Println("a different goroutine unlocked the mutex")
}
$ go build -trimpath -o p7.bin p7_cross_goroutine.go
$ ./p7.bin; echo "exit status $?"
a different goroutine unlocked the mutex
exit status 0
The release succeeded because the mutex was locked when it arrived - the state rule was satisfied, and the goroutine rule does not exist. If a program with this shape still hits the fatal error, the cause is the count, not the handoff: the goroutine ran before the lock was taken, ran after another release already released it, or ran twice.
The RWMutex versions: two different messages
sync.RWMutex has two release operations, and each has its own fatal message - neither of them is this guide's title line, so a log search for the Mutex wording will miss them. The read-side release undoes one RLock, and the documentation makes it a run-time error if the RWMutex is not locked for reading on entry. With no readers at all:
package main
import (
"fmt"
"sync"
)
func main() {
var rw sync.RWMutex
fmt.Println("about to RUnlock a RWMutex with no readers")
rw.RUnlock()
fmt.Println("after the RUnlock")
}
$ go build -trimpath -o p8.bin p8_rw_runlock.go
$ GOTRACEBACK=none ./p8.bin; echo "exit status $?"
about to RUnlock a RWMutex with no readers
fatal error: sync: RUnlock of unlocked RWMutex
exit status 2
The write side has its own wording. The write-side release on an RWMutex frees the write lock, and it is a run-time error if the mutex is not locked for writing on entry:
package main
import (
"fmt"
"sync"
)
func main() {
var rw sync.RWMutex
fmt.Println("about to Unlock a RWMutex that is not write-locked")
rw.Unlock()
fmt.Println("after the Unlock")
}
$ go build -trimpath -o p9.bin p9_rw_unlock.go
$ GOTRACEBACK=none ./p9.bin; echo "exit status $?"
about to Unlock a RWMutex that is not write-locked
fatal error: sync: Unlock of unlocked RWMutex
exit status 2
And the doubled release mirrors the plain mutex: one RLock, one legal read-side release, and a second read-side release that has no reader left to answer it:
package main
import (
"fmt"
"sync"
)
func main() {
var rw sync.RWMutex
rw.RLock()
fmt.Println("read-locked")
rw.RUnlock()
fmt.Println("read-unlocked once")
rw.RUnlock()
fmt.Println("after the second RUnlock")
}
$ go build -trimpath -o p10.bin p10_rw_double_runlock.go
$ GOTRACEBACK=none ./p10.bin; echo "exit status $?"
read-locked
read-unlocked once
fatal error: sync: RUnlock of unlocked RWMutex
exit status 2
The fixes are the same two shapes, applied per side: defer the read-side release immediately after the RLock (and the write-side release immediately after the write Lock), and guard any release path that can be reached more than once. One RWMutex subtlety is worth keeping straight while you do: the read-side release answers a read lock and the write-side release answers a write lock, and they are not interchangeable - releasing the wrong side is the same class of unmatched call, under whichever of the two messages applies.
Decision summary
- The crash line is
fatal error: sync: unlock of unlocked mutex: a release call arrived while the mutex was not locked - find the lock that never ran or the release that ran twice; do not add arecover, it cannot engage. - The crash line instead reads the read-side fatal message or the write-side fatal message: the same unmatched-release bug on an
RWMutex, on its read side or its write side respectively. - A deferred
recoveraround the suspect code changed nothing, and deferred functions after the call never ran: consistent with a fatal error, not a panic - the pairing itself is the only fix. - The lock and its release live in one function:
mu.Lock()followed immediately bydefer mu.Unlock(), and no other release call for that hold anywhere. - The release lives in a separate cleanup or close path that can be called more than once: make it conditional on a held flag that is set at the lock and cleared at the release, owned by the same lifecycle owner.
- The release is called from a different goroutine than the lock: legal by itself - look instead for the release running before the lock, after another release, or twice.
Checklist
- Every release call in the code answers a
Lockthat is still held at that point - counted along every path, including error paths and early returns. - In-function holds use the pair
Lockthen deferring the release, written together, with no second hand-placed release for the same hold. - Any release path that can run more than once checks a held flag - or is restructured so it can only run once - before it makes the release call.
- No
recoveris being relied on anywhere as protection against this error; it cannot run, and neither can the deferred functions around the call. RWMutexreleases match their side: the read-side release for eachRLock, the write-side release for the writeLock, each exactly once.- The fixed program runs to completion, and a deliberate second release on a guarded path is a no-op rather than a crash.
Related guides
- Negative WaitGroup Counter Panic Fix - the sibling accounting error in the same package: subtractions outnumbering additions on a
sync.WaitGroup, where the extra call is aDoneinstead of a release call. - Close of Closed Channel Panic Fix - the channel version of the doubled release: a second
closeon an already-closed channel, fixed by giving the close exactly one owner.
Sources
- Go
syncpackage,Mutex.Unlock- the contract this error enforces: that method releases the mutex, it is a run-time error if the mutex is not locked on entry to it, the zero value for aMutexis a mutex that is not locked, and a locked mutex is not associated with a particular goroutine - one goroutine may lock it and arrange for another to release it. - Go
syncpackage,RWMutex.RUnlockandRWMutex.Unlock- the read and write release contracts: the read-side release undoes a singleRLockcall and is a run-time error if theRWMutexis not locked for reading on entry; the write-side release frees the write lock and is a run-time error if it is not locked for writing on entry. - Go
builtinpackage,recoverandpanic- the boundary the fatal error sits outside:recovermanages the behavior of a panicking goroutine and stops a panicking sequence, andpanicis documented as the call that starts such a sequence - a sequence the mutex's fatal error never begins, which is why the deferredrecoverin this guide's third program never executes.
Keep Exploring
The full Go hub \u2014 slices and maps, concurrency, and the standard library.
Every guide on the site in one list, grouped by topic.
Every browser-only checker and verifier on the site.
The C++, Python, Sysadmin, Rust, Go, and TypeScript hubs.