<!--
{
  "availability" : [
    "iOS: 2.0.0 -",
    "iPadOS: 2.0.0 -",
    "macCatalyst: 13.0.0 -",
    "macOS: 10.0.0 -",
    "tvOS: 9.0.0 -",
    "visionOS: 1.0.0 -",
    "watchOS: 2.0.0 -"
  ],
  "documentType" : "symbol",
  "framework" : "Foundation",
  "identifier" : "/documentation/Foundation/NSLock",
  "metadataVersion" : "0.1.0",
  "role" : "Class",
  "symbol" : {
    "kind" : "Class",
    "modules" : [
      "Foundation"
    ],
    "preciseIdentifier" : "c:objc(cs)NSLock"
  },
  "title" : "NSLock"
}
-->

# NSLock

An object that coordinates the operation of multiple threads of execution within the same application.

```
class NSLock
```

## Overview

An [`NSLock`](/documentation/Foundation/NSLock) object can be used to mediate access to an application’s global data or to protect a critical section of code, allowing it to run atomically.

> Warning:
> The ``doc://com.apple.foundation/documentation/Foundation/NSLock`` class uses POSIX threads to implement its locking behavior. When sending an unlock message to an ``doc://com.apple.foundation/documentation/Foundation/NSLock`` object, you must be sure that message is sent from the same thread that sent the initial lock message. Unlocking a lock from a different thread can result in undefined behavior.

You should not use this class to implement a recursive lock. Calling the `lock` method twice on the same thread will lock up your thread permanently. Use the [`NSRecursiveLock`](/documentation/Foundation/NSRecursiveLock) class to implement recursive locks instead.

Unlocking a lock that is not locked is considered a programmer error and should be fixed in your code. The [`NSLock`](/documentation/Foundation/NSLock) class reports such errors by printing an error message to the console when they occur.

## Topics

### Acquiring a Lock

[`lock(before:)`](/documentation/Foundation/NSLock/lock(before:))

Attempts to acquire a lock before a given time and returns a Boolean value indicating whether the attempt was successful.

[`try()`](/documentation/Foundation/NSLock/try())

Attempts to acquire a lock and immediately returns a Boolean value that indicates whether the attempt was successful.

### Naming the Lock

[`name`](/documentation/Foundation/NSLock/name)

The name associated with the receiver.



---

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)