Fiber semaphore object
The semaphore object manages an internal counter, which decreases by one after calling acquire or wait, and increases by one after calling release or post. The counter will not decrease to a negative number, because acquire and wait will sleep the current fiber when the value is 0, until other fibers increase the value of the counter through release or post.
Common occasions for semaphores are to limit the concurrent use of resources and the application of the producer/consumer model.
Take database requests as an example to limit the concurrent use of resources:
1 2 3 4 5 6 7 8 9 10var maxconnections = 5; var l = new coroutine.Semaphore(maxconnections); ...... l.acquire(); var conn = connectdb() ..... conn.close(); l.release();
The producer/consumer model usually uses semaphores in conjunction with queues. The producer adds data to the queue and posts a signal, and the consumer waits for the signal first, gets the signal and then goes to the queue to query and fetch the data.
1new Semaphore(Integer value = 1);
- value : Integer, the initial value of the counter
Waiting for a semaphore, equivalent to acquire(true)
Release a semaphore, which is equivalent to release()
Try to acquire a signal. If it cannot be acquired, return immediately and return false, which is equivalent to acquire(false)
- Boolean , return true if successful
Acquire lock ownership
1Boolean Semaphore.acquire(Boolean blocking = true);
- blocking : Boolean, specify whether to wait, wait when true, the default is true
- Boolean , returns whether the lock is successfully acquired, true means successful acquisition
The acquire method is used to acquire the ownership of the lock. When the lock is in an acquireable state, this method returns true immediately.
When the lock is unavailable and blocking is true, the current fiber goes to sleep. When other fibers release the lock, this method returns true.
When the lock is not available and blocking is false, the method returns false.
Release lock ownership
This method will release the ownership of the lock. If the current fiber does not own the lock, this method will throw an error.
Query the current number of waiting tasks
- Integer , returns the number of tasks
Returns the string representation of the object, generally returns "[Native Object]", the object can be re-implemented according to its own characteristics
- String , returns the string representation of the object
Returns the JSON format representation of the object, generally returns a collection of readable attributes defined by the object
1Value Semaphore.toJSON(String key = "");
- key : String, unused
- Value , returns a value containing JSON serializable