Conditional lock, linux conditional lock

Source: Internet
Author: User

Conditional lock, linux conditional lock
The ReentrantLock class has a method newCondition used to generate a Condition object for this lock object, which implements the Condition interface. Condition provides a set of thread communication mechanisms, such as await and signal ..
1. Applicable scenarios when a thread obtains the lock object, but some conditions are not met, it is necessary to wait on this condition until the conditions are met to continue execution, the conditional lock is required. In this case, the thread actively blocks a condition. When other threads find that the condition changes, they can wake up the thread blocking the condition.
2. The following is a sample code from JDK. You must obtain a lock object before calling the condition object of the lock to block it.

class BoundedBuffer {   final Lock lock = new ReentrantLock();   final Condition notFull  = lock.newCondition();    final Condition notEmpty = lock.newCondition();    final Object[] items = new Object[100];   int putptr, takeptr, count;   public void put(Object x) throws InterruptedException {     lock.lock();      try {       while (count == items.length)         notFull.await();       items[putptr] = x;       if (++putptr == items.length) putptr = 0;       ++count;       notEmpty.signal();     } finally {       lock.unlock();     }   }   public Object take() throws InterruptedException {     lock.lock();     try {       while (count == 0)         notEmpty.await();       Object x = items[takeptr];       if (++takeptr == items.length) takeptr = 0;       --count;       notFull.signal();       return x;     } finally {       lock.unlock();     }   } }
Note that the above Code first uses lock. lock obtains the lock Object and finds that the condition is not met (count = items. length), the cache is full, and data cannot be written into it. In this case, the condition object notFull is called. await () is blocked. If the conditions are met, data will be written to the cache, And the thread waiting for non-empty cache will be notified, notEmpty. signal.
In this way, the communication between the read thread and the write thread is realized.
3. Impact of thread blocking on the lock in the above example, the thread first obtains the Lock Object and then calls notFull. await to implement thread blocking. In this case, the thread with the lock is blocked, and whether it may cause a deadlock. Of course, the answer is no. The reason is that the thread first releases the current lock in the await method of the condition object, and then enters the blocking state for the thread to wake up.
4. The relationship between conditional wait and wake-up of threads and lock objects is described in ReentrantLock parsing. The AbstractQueuedSynchronizer maintains a queue internally, and the thread waiting for the lock is in this queue. Similarly, ConditionObject maintains a queue, and the thread waiting for the condition also forms a queue.
When the ready-made call of await is blocked, it will be added to the waiting queue within the ConditionObject. Note that the thread is automatically blocked. The thread will be blocked until it is awakened or interrupted by other threads.
When other threads call signal to wake up the blocked thread, the first node in the waiting queue is removed from the queue and added to the waiting queue in the AbstractQueuedSynchronizer Lock Object. Why is it in the lock wait queue? Because after a thread is awakened, it does not mean it can be executed immediately. At this point, other threads may have this lock, and there are already ready-made waiting for this lock. Therefore, the Awakened thread needs to enter the lock wait queue. After the execution of the preceding thread is complete, in order to continue subsequent operations.
See 5. Whether the thread can be in the waiting queue of the condition object and the waiting queue of the lock object at the same time
No. Only the await method of the condition object can be called by the thread to enter the waiting queue of the condition object. The prerequisite for a thread to call the await method is that the thread has obtained the lock, so the thread enters the waiting queue of the condition object in the locked state, the thread with the lock, that is, the running thread, is not in the waiting queue of the lock object. Only when a thread tries to obtain the lock and the lock is occupied by other threads will the thread enter the lock wait queue and wait for the thread with the lock to complete the execution, the lock is awakened when it is released.
6. Implementation Principle
The related code can be seen in the ConditionObject class of AbstractQueuedSynchronizer. ConditionObject has two attributes: firstWaiter and lastWaiter, pointing to the header and end of the condition object waiting for the queue respectively. Each Node in the queue is a Node (internal class of AbstractQueuedSynchronizer) object that is passed down between nextWaiter of the Node object. Therefore, the waiting queue of the condition object is a one-way linked list.
The following is the source code of await. Public  Final  VoidAwait () ThrowsInterruptedException { If(Thread. Interrupted()) Throw  NewInterruptedException (); Node node = addConditionWaiter (); IntSavedState = fullyRelease (node ); IntInterruptMode = 0; While(! IsOnSyncQueue (node) {LockSupport. Park( This); If(InterruptMode = checkInterruptWhileWaiting (node ))! = 0) Break;} If(AcquireQueued (node, savedState) & interruptMode! = THROW_IE) InterruptMode = REINTERRUPT; If(Node. nextWaiter! = Null) UnlinkCancelledWaiters (); If(InterruptMode! = 0) reportInterruptAfterWait (interruptMode );}
The first is to call addConditionWaiter to add the current thread to the waiting queue of the condition object, then fullyRelease to release the lock, and then use isOnSyncQueue to check whether the current thread node is in the waiting queue of the lock object. Why is this check required? When a thread is awakened by signal, it is first added to the waiting queue of the lock object. If the lock object is not in the waiting queue, it indicates that the event has not occurred (that is, there is no signal method not called), so the thread needs to be blocked to wait for the wake-up.
The construction of the waiting queue is completed in the addConditionWaiter method. The Code is as follows:
PrivateNode addConditionWaiter () {Node t = lastWaiter; // If lastWaiter is canceled, clean out. If(T! = Null& T. waitStatus! = Node. CONDITION) {UnlinkCancelledWaiters (); t = lastWaiter;} Node node = NewNode (Thread. CurrentThread(), Node. CONDITION); If(T = Null) FirstWaiter = node; ElseT. nextWaiter = node; lastWaiter = node; ReturnNode;} threads are added to the queue in the same order as the time when they are added. The newly added thread is at the end of the queue.
Next let's take a look at the thread wake-up Public  Final  VoidSignal (){ If(! IsHeldExclusively ()) Throw  NewIllegalMonitorStateException (); Node first = firstWaiter; If(First! = Null) DoSignal (first );}
The wake-up operation is actually completed through doSignal. Note that the node pointed to by firstWaiter is passed here, that is, the wake-up operation starts from the queue header. The queue is a FIFO queue.
Private  VoidDoSignal (Node first ){ Do{ If(FirstWaiter = first. nextWaiter) = Null) LastWaiter = Null; First. nextWaiter = Null;} While(! TransferForSignal (first) & (first = firstWaiter )! = Null);}
The doSignal method removes the first node from the waiting queue of the condition object, and then finally moves to transferForSignal for operations. Final  BooleanTransferForSignal (Node node) {/** If cannot change waitStatus, the node has been canceled .*/ If(! CompareAndSetWaitStatus(Node, Node. CONDITION, 0 )) Return  False;
/** Splice onto queue and try to set waitStatus of predecessor to * indicate that thread is (probably) waiting. if canceled or * attempt to set waitStatus fails, wake up to resync (in which * case the waitStatus can be transiently and harmlessly wrong ). */Node p = enq (node ); IntWs = p. waitStatus; If(Ws> 0 |! CompareAndSetWaitStatus(P, ws, Node. SIGNAL) LockSupport. Unpark(Node. thread ); Return  True;}
The enq method is used to add the node where the thread is located to the Lock Object waiting queue. In this way, when the conditions are appropriate, the thread is awakened, the lock is obtained, and then executed.
How can I lock a disk that has been unlocked with a bitlocker lock without restarting?

Manage-bde-lock x:
X is your drive letter. Run CMD with the administrator account. In the black window, enter OK. You can also write a bat command by yourself.

Conditions for the automatic hydraulic transmission, locking the clutch into the locking Condition

Generally, it is in the case of higher transmission ratio. The specific condition is determined by the ratio of the torque converter & coupler & Mechanical connection (Yita = 1) to the point of intersection of the variable moment coefficient curve (because the speed multiplied torque is efficiency, principle is the most efficient ). Here is a picture for ease of understanding:
Image.baidu.com/...type1_2

The torque converter can provide additional torque when the difference between the input speed and the output speed is large, which can be used for increased torsion, so it can significantly improve the starting performance of the car. However, when the two are close to each other, they cannot increase or even transmit the torque. In addition, there is a hydraulic loss between the turbine and the pump wheel of the torque converter, and the efficiency is far less than that of the mechanical transmission, so in order to improve the mechanical efficiency of high transmission ratio, the locking device is used.

Generally, the torque converter with a lock clutch also has a one-way clutch, so the conversion of working conditions should be like this:
Low speed, torque converter, low output speed, high torque
As the turbine speed increases, the flow opposite the impact of the Guide Wheel, no longer increased torsion, the single clutch will lock the guide wheel, so as to enter the working condition of the coupler
When the speed is further increased and the efficiency of the torque converter is reduced, the clutch is locked and becomes a rigid connection. The efficiency of the torque converter is 1.

Hope to help you understand it!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.