From Xojo Documentation

Revision as of 14:41, 1 October 2018 by PLefebvre (talk | contribs) (Examples)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

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.

Sample Code

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:

// Allow only a single thread to access the file at a time
FileAccess = New Semaphore(1)

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

// This will Suspend this thread if another has the lock
// When it is released, this thread will continue to run

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

// When you are finished, release the semaphore

See Also

CriticalSection, Mutex, Thread classes.