<!--
{
  "availability" : [
    "iOS: 18.0.0 -",
    "iPadOS: 18.0.0 -",
    "macCatalyst: 18.0.0 -",
    "macOS: 15.0.0 -",
    "tvOS: 18.0.0 -",
    "visionOS: 2.0.0 -",
    "watchOS: 11.0.0 -"
  ],
  "documentType" : "symbol",
  "framework" : "Swift",
  "identifier" : "/documentation/Synchronization/Mutex/withLock(_:)",
  "metadataVersion" : "0.1.0",
  "role" : "Instance Method",
  "symbol" : {
    "kind" : "Instance Method",
    "modules" : [
      "Synchronization"
    ],
    "preciseIdentifier" : "s:15Synchronization5MutexVAARi_zrlE8withLockyqd__qd__xzYuqd_0_YKYTXEqd_0_YKs5ErrorRd_0_Ri_d__r0_lF"
  },
  "title" : "withLock(_:)"
}
-->

# withLock(_:)

Calls the given closure after acquiring the lock and then releases
ownership.

```
borrowing func withLock<Result, E>(_ body: (inout sending Value) throws(E) -> sending Result) throws(E) -> sending Result where E : Error, Result : ~Copyable
```

## Parameters

`body`

A closure with a parameter of `Value`
that has exclusive access to the value being stored within
this mutex. This closure is considered the critical section
as it will only be executed once the calling thread has
acquired the lock.

## Return Value

The return value, if any, of the `body` closure parameter.

## Discussion

This method is equivalent to the following sequence of code:

```
mutex.lock()
defer {
  mutex.unlock()
}
return try body(&value)
```

> Warning: Recursive calls to `withLock` within the
> closure parameter has behavior that is platform dependent.
> Some platforms may choose to panic the process, deadlock,
> or leave this behavior unspecified. This will never
> reacquire the lock however.

---

Copyright &copy; 2026 Apple Inc. All rights reserved. | [Terms of Use](https://www.apple.com/legal/internet-services/terms/site.html) | [Privacy Policy](https://www.apple.com/privacy/privacy-policy)