---
title: NSLock
framework: foundation
role: symbol
role_heading: Class
path: foundation/nslock
---

# NSLock

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

## Declaration

```swift
class NSLock
```

## Overview

Overview An 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 NSLock class uses POSIX threads to implement its locking behavior. When sending an unlock message to an 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 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 class reports such errors by printing an error message to the console when they occur.

## Topics

### Acquiring a Lock

- [lock(before:)](foundation/nslock/lock(before:).md)
- [try()](foundation/nslock/try().md)

### Naming the Lock

- [name](foundation/nslock/name.md)

## Relationships

### Inherits From

- [NSObject](objectivec/nsobject-swift.class.md)

### Conforms To

- [CVarArg](swift/cvararg.md)
- [CustomDebugStringConvertible](swift/customdebugstringconvertible.md)
- [CustomStringConvertible](swift/customstringconvertible.md)
- [Equatable](swift/equatable.md)
- [Hashable](swift/hashable.md)
- [NSLocking](foundation/nslocking.md)
- [NSObjectProtocol](objectivec/nsobjectprotocol.md)
- [Sendable](swift/sendable.md)
- [SendableMetatype](swift/sendablemetatype.md)

## See Also

### Threads and Locking

- [Thread](foundation/thread.md)
- [NSLocking](foundation/nslocking.md)
- [NSRecursiveLock](foundation/nsrecursivelock.md)
- [NSDistributedLock](foundation/nsdistributedlock.md)
- [NSConditionLock](foundation/nsconditionlock.md)
- [NSCondition](foundation/nscondition.md)
