From Xojo Documentation

Revision as of 15:13, 25 May 2018 by PLefebvre (talk | contribs) (Notes)
You are currently browsing the old Xojo documentation site. Please visit the new Xojo documentation site!

Class (inherits from Object)

Used to control access to resources in a multithreaded environment.

Release TrySignal


Constructor(NumResources as Integer)


A Semaphore is an object that can be used to coordinate access to a shared resource.

To acquire the ownership of a semaphore, a thread calls the Signal or TrySignal methods. If the Semaphore isn't owned, the thread acquires ownership, which means you have a lock on it. Otherwise the thread is forced to wait until the Semaphore is released via the Release method by the owning thread.

Every time you successfully obtain an ownership lock on the resource, the Semaphore will decrement its internal count of available resources. When there are no more resources, threads that request ownership locks will begin to block and wait for resources. This is why you can specify the initial count of resources -- to give you more control over the behavior of the Semaphore.

The Semaphore class is different from the CriticalSection and Mutex classes in this way: calling Signal in the same thread will cause the counter to decrement. If you call Signal recursively, you will cause the application to hang.


This example uses a Semaphore to ensure that only one thread at a time writes to a file.

Add a public property to the App class:

FileAccess As Semaphore

And in the Open event handler, initialize it:

FileAccess = New Semaphore(1)

In the thread, check the FileAccess semaphore to see if you can write to the file:

Dim accessingFile As Boolean

If App.FileAccess.TrySignal Then
accessingFile = True
// File is locked by another thread so
// Sleep and try again
End If
Loop Until accessingFile

// Now you can open the file for writing
WriteDataToFile // Supply your own code here

// When you are finished, release the semaphore

See Also

CriticalSection, Mutex, Thread classes.