/* ----------------------------------------------------------------------------- Copyright 2021 Kevin P. Barry Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ----------------------------------------------------------------------------- */ // Author: Kevin P. Barry [ta0kira@gmail.com] // Blocks a thread until a condition is met. // // Notes: // - Mutex logic is exposed so that it can be used to avoid race conditions with // the thread signalling continuation. (For example, if blocking behavior is // conditioned on the availability of input from another thread.) @value interface ConditionWait { refines Mutex // Block the current thread. // // Notes: // - The current thread *must* lock() before wait() and unlock() after. The // program could deadlock or crash otherwise. // // Example: // // scoped { // MutexLock lock <- MutexLock.lock(threadWait) // } cleanup { // \ lock.freeResource() // } in \ threadWait.wait() // // // continue processing here wait () -> (#self) // Block the current thread for at most the specified amount of time. // // Args: // - Float: Timeout in seconds. // // Returns: // - Bool: Set to false iff the timeout was reached. // // Notes: // - The current thread *must* lock() before timedWait() and unlock() after. // The program could deadlock or crash otherwise. // // Example: // // scoped { // MutexLock lock <- MutexLock.lock(threadWait) // } cleanup { // \ lock.freeResource() // } in Bool success <- threadWait.timedWait(10.0) // // if (success) { // // continue processing here // } else { // // error handling // } timedWait (Float) -> (Bool) } // Resumes thread waiting for a condition. // // Example: // // scoped { // MutexLock lock <- MutexLock.lock(conditionResume) // } cleanup { // \ lock.freeResource() // } in { // // prepare state for threads, e.g., read data from disk // } // // // signal threads to continue // \ conditionResume.resumeAll() @value interface ConditionResume { refines Mutex // Resume all of the threads waiting for the associated condition. resumeAll () -> (#self) // Resume one of the threads waiting for the associated condition. resumeOne () -> (#self) } // Provides a single resume mechanism for multiple waiting threads. concrete ThreadCondition { refines ConditionWait refines ConditionResume // Create a new condition. @type new () -> (ThreadCondition) }