Core Function ThreadLock

From Sputnik Wiki
Jump to: navigation, search
ThreadLock( <lockname> ) {}

Contents

Description

Locks a given section of code allowing only one thread to execute it at a time

Parameters

lockname

This can be any name you wish however if you wish your lock to also lock other sections of your code you must make the lock names the same.

The same name will block all threads that try to access it no matter how many there are.

Return Value

None.

Remarks

This thread lock is pretty safe and shouldnt cause any problems such as Deadlocks unless you serious write some very stupid code.

Example

Notice in this example only thread 1 will be allowed to execute this code at a time after 3 seconds the lock will disengage and another thread will be allowed to take over.

// Spawn 2 threads
ThreadCreate("th1", "ThreadFunc();");
ThreadCreate("th2", "ThreadFunc();");
 
inputc();
 
Function ThreadFunc() // Both threads will try use this function
{
	While(True)
	{
		$iCount = 0;
		// only allow one thread to run this code at a time
		// the rest will queue until its their turn
		ThreadLock( "Testy" )
		{
			while(true)
			{
				if($iCount >= 3)
				{
					break; // Allow the next thread
				}
				println("Hello from thread '" . ThreadName() . "'");
				sleep(1000);
				$iCount++;
			}
		}
	}
}

This is very useful since it allows you to setup classes and objects that you only want 1 thread to access at a time since if multiple threads tired to write to it all at once it would cause a crash

Personal tools
Namespaces
Variants
Actions
Navigation
Toolbox