223 of 286
209 Semaphore Type Function returning Boolean Invocation Semaphore(var) Parameter Method Type Description var ByRef Boolean A variable used as a semaphore. Discussion This function will test the provided variable and if it is already True, the function will return False. Otherwise, if the semaphore variable is False, the call will set it to True and return True. This is referred to in computer science as an “atomic test and set” operation. A semaphore is a signaling and synchronization mechanism used in multi-tasking systems. The idea is that if two or more tasks each want to use a particular resource they first request ownership of a semaphore. The request mechanism ensures that even if multiple requests occur near the same time, one and only one request will be satisfied. Therefore, the task that is granted the semaphore will have exclusive access to the resource until it has completed its objective. Subsequently, other tasks can request the semaphore and, if they receive it, they can perform their objective. Thus you can see that a particular semaphore can control access to some set of resources that you define. Your system may have multiple semaphores, each controlling access to a set of resources. Note, however, that if multiple semaphores are required to complete an operation the possibility of deadlock exists. This problem will occur if one task obtains one semaphore, another task obtains another semaphore and then both tasks wait for the other semaphore to be available. In order for this mechanism to be effective, the same semaphore variable must be used by each task for gaining access to a particular set of resources. For this reason, the semaphore variable passed to Semaphore() will almost always be a global variable but it may be public or private as suits your application. The semaphore variable must be initially False, otherwise no Semaphore() request on that semaphore can ever succeed. Also, after a task has successfully gotten the semaphore and has finished using the related resources, the semaphore must be set False again so that a future Semaphore() call will succeed. Example Dim serSem as Boolean serSem = False ' wait until we get the semaphore Do While (Not Semaphore(serSem)) Call Delay(0.5) Loop ' now we can use the controlled resources [add code here] ' finished with the resources, release the semaphore serSem = False