Skip to main content

Thread

Threads utilize the coroutines of the underlying script VM and are designed to execute loops or delays without blocking the game. A thread exists until its code has finished executing or it is manually terminated using Kill.

info

All threads run sequentially (synchronously) on the main thread. Therefore, there is no need to worry about writing thread-safe code.

warning

If you use an infinite loop inside a thread, you must call Thread.Pause() (even Thread.Pause(0) is sufficient). Failing to do so will freeze the entire game or server, as the thread will never yield control back to the main thread.

Quick Reference

NameTypeDescription
CreateSharedCreates a new thread with a function that is executed asynchronously.
PauseSharedPauses the current thread for the specified duration.
KillSharedKills the specified thread on the next script tick.
IsAliveSharedReturns whether the specified thread is currently alive and running.

Shared Functions

Create

Creates a thread with a function that is executed on the next script tick.

int threadId = Thread.Create(function threadFunc, any ...)

Example:

Events.Subscribe("sessionInit", function()
Thread.Create(function()
-- Get player model hash key.
local playerModel = Game.GetHashKey("M_Y_MULTIPLAYER")

-- Request model.
Game.RequestModel(playerModel)

-- Wait until model loaded.
while not Game.HasModelLoaded(playerModel) do
Game.RequestModel(playerModel)
Thread.Pause(0)
end

-- Change player model.
Game.ChangePlayerModel(Game.GetPlayerId(), playerModel)

-- Release model.
Game.MarkModelAsNoLongerNeeded(playerModel)
end)
end)

Pause

Pauses the current thread for the specified duration.

Thread.Pause(int milliseconds)

warning

This function can only be used within a running thread.

Example:

Events.Subscribe("scriptInit", function()
Thread.Create(function()
while true do
Thread.Pause(5000)

-- This message is sent every 5 seconds.
Chat.AddMessage("5 seconds are over.")
end
end)
end)

Kill

Kills the specified thread on the next script tick.

Thread.Kill(int threadId)


IsAlive

Returns whether the specified thread is currently alive and running.

bool alive = Thread.IsAlive(int threadId)

warning

A thread marked for termination (via Kill) will continue to return true until it is actually terminated during the next script tick.