# async.mutex (Shared)

> Runs a function in a new async thread, as `async.thread` does, but does not start while another thread started from the same line of code, with the same `key`, is still running.

- **Platform**: MY Multiplayer (MYMP)
- **Kind**: Lua Function
- **Side**: Shared
- **Category**: Timers and async
- **URL**: https://wiki.mymp.gg/en/async.mutex

## Syntax

```lua
any async.mutex(function func [, any key = nil])
```

## Parameters

| Name | Type | Description |
| --- | --- | --- |
| `func` | `function` | The function the thread runs. |
| `key` | `any` | A value that keeps the same line's locks apart, such as a player. It is turned into text as `tostring` does. *(default: `nil`)* |

## Returns

The thread, or `false` if a thread from the same line and the same `key` has not ended yet.

## Example

```lua
addCommandHandler("save", function(player)
    local started = async.mutex(function()
        async.wait(2000)
        outputDebugString(getPlayerName(player) .. " saved")
    end, player)

    if not started then
        outputDebugString(getPlayerName(player) .. " is already saving")
    end
end)
```

## See also

- [async.thread (Shared)](https://wiki.mymp.gg/en/async.thread.md): Runs a function in a new async thread, right away. The call returns when the function ends or first pauses, as with async.wait.
- [async.status (Shared)](https://wiki.mymp.gg/en/async.status.md): Tells what state an async thread of this resource is in.
