Skip to main content

What are Threads?

Threads in RedM are asynchronous processes that run independently without blocking the main script execution. They’re essential for creating continuous loops, delays, and background tasks.
Threads allow multiple things to happen β€œat the same time” without freezing the game!

CreateThread

The primary way to create a thread in RedM:

Basic Thread Example

Output:

Wait() Function

Wait(milliseconds) pauses the current thread without freezing the game.
NEVER use Wait(0) in a loop unless absolutely necessary! It runs every frame and kills performance.

Good Wait Times


Infinite Loops

Threads that run forever:
Real Example from RSG:

Conditional Loops

Loop Until Condition

Loop While Condition


SetTimeout

Run code once after a delay (doesn’t block):
Real Example from RSG:

Multiple Threads

You can run multiple threads simultaneously:

Breaking Out of Loops

Using break

Using return


Thread Control Patterns

Start/Stop Thread

Restart Thread


Common Thread Patterns

Pattern 1: Entity Proximity Check

Check if player is near an entity/location:

Pattern 2: Player State Monitor

Monitor player state changes:

Pattern 3: Timed Buff/Debuff

Apply effect for a duration:

Pattern 4: Cooldown System

Prevent spam by adding cooldowns:

Pattern 5: Resource Load Wait

Wait for other resources to load:

Performance Optimization

Dynamic Wait Times

Adjust wait time based on conditions:

Sleep When Inactive


Real RSG Framework Examples

Example 1: Duty System

Example 2: Health/Hunger System

Example 3: Auto-Save


Debugging Threads

Thread Identifier

Performance Monitor


Summary

Always use Wait() in loops to prevent freezing the game!

Best Practices

  1. Use appropriate wait times (avoid Wait(0))
  2. Break long operations into chunks
  3. Clean up threads when no longer needed
  4. Use dynamic wait times based on conditions
  5. Monitor thread performance

Next Steps


Need more help? Join the RSG Framework Discord!