From Xojo Documentation
|You are currently browsing the old Xojo documentation site. Please visit the new Xojo documentation site!|
Used to control access to resources in a multithreaded environment.
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:
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:
// 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