"Sputnik" help  
Sputnik Help
Rule Synchronized

Description

This demonstrates how to create a synchronized function that can only be executed by one thread at a time.

Before reading this section make sure to read all User Functions and understand it.

Remarks

The synchronized rule in Sputnik allows you to create functions that can only be executed by one thread at a time. By applying the s flag to a function, you ensure that multiple threads cannot simultaneously enter and execute the function's code.

When a function is synchronized, it becomes thread-safe, meaning it can be safely accessed by multiple threads without causing concurrency issues or data corruption. Synchronization ensures that only one thread can execute the synchronized function at any given time, while other threads wait for their turn to access the function.

In the provided example, a function named Test is marked as synchronized using the s flag. This function simulates some work by printing messages and sleeping for a specified duration. The main thread creates a separate thread that calls the Test function. As a result, when the main thread tries to execute Test, it waits until the other thread completes its execution.

By synchronizing the Test function, you ensure that the function is executed sequentially, avoiding potential race conditions or conflicts that could arise from concurrent access. This synchronization mechanism helps maintain data integrity and consistency when multiple threads interact with the same function.

Using the synchronized rule is beneficial in scenarios where shared resources or critical sections need to be accessed safely by multiple threads. It provides a controlled and synchronized execution flow, preventing concurrent modifications and ensuring thread safety.

By applying the synchronized rule to relevant functions, you can effectively manage thread access and maintain the integrity of shared data or critical operations.

Related

User Functions, Lock Statement

Example

Example :

// Create a thread that runs on the function
ThreadCreate('testThread', &Test);
sleep(1000); // give the thread enough time to reach the function

"s" Function Test()
{
    say "Test function running";
    sleep(5000); // Sleep for 5 seconds
    say "Test function ended";
}

say "Trying to run Test function...";
// after the above text there will be a 4 second pause
// since the function is waiting for the other thread to
// end before allowing our thread to call it
Test();

// PRINTS
// Test function running
// Trying to run Test function...
// Test function ended
// Test function running
// Test function ended

As you can see each thread could only run the function if the other was not running the function.

This is a safe way of making sure only one thread runs the function at a time.


Contact
Cheryl (uberfox@hotmail.com)
Homepage
http://ubersoft.org