CriticalObject()

Auto Hotkey

CriticalObject

Built-in function to enwrap an object for multi-thread use. Such objects can be used from multiple threads without causing a crash.

OutputVar := CriticalObject(Object, lpCriticalSection)
Function Example: obj := CriticalObject(MyCriticalObject)

Parameters

OutputVar

The name of the variable in which to store the created object.

Object

Existing Object or CriticalObject to use, this can be also a pointer.
When CriticalObject is given, its CriticalSection will be used and second parameter will be ignored.
When this parameter is empty new object will be created and used.

lpCriticalSection

Pointer to a CriticalSection to use. When this parameter is omitted new CriticalSection will be created unless CriticalObject was given in first parameter, then its CriticalSection will be used.

General Remarks

How does it work:

  • First the CriticalSection is locked so the object cannot be used in other threads
  • Then the referenced object is invoked
  • Afterwards critical section is unlocked so other threads can use the object again

To retrieve the original object from CriticalObject use:

object := CriticalObject(CriticalObject,1)

To retrieve the pointer to CriticalSection use:

lpCriticalSection := CriticalObject(CriticalObject,2)

When last reference to internal object is deleted, CrticalSection is deleted as well.

Related

Object

Examples

obj := CriticalObject() ; Create new critical object
Loop, 4 ; Create 4 Threads.
 AhkThread%A_Index% := AhkThread("obj:=CriticalObject(" (&obj;) ")`nLoop`nobj[" A_Index "]:= A_Index")
 
Loop ; Show current content of object.
 ToolTip, % obj.1 "`n" obj.2 "`n" obj.3 "`n" obj.4
Esc::ExitApp