简体   繁体   English

线程调度和同步

[英]Thread scheduling and synchronization

Is it possible for the thread scheduler to unschedule a thread holding the lock to a synchronized block and is in the middle of executing it? 线程调度程序是否可以取消将锁锁定到同步块并处于执行中间的线程的调度? If yes then does the unscheduling leads to thread releasing the lock? 如果是,那么非调度导致线程释放锁吗? Assume thread doesn't call method such as wait/yield etc. 假设线程不调用诸如wait/yield等方法。

I have been trying to understand how synchronized block helps in read-update-write operation? 我一直在尝试了解同步块如何在读-更新-写操作中提供帮助? If the thread which enters the synchronized block can't be unscheduled then it's easier to understand but if it can be then the issue of visibility comes as it might be the case that variable has been updated but not written to the main memory by thread and thread scheduler unschedules it and other thread gets the lock and updated the variable in the main memory. 如果进入同步块的线程不能被调度,那么它更容易理解,但是如果可以,那么可见性问题就来了,因为变量可能已经被更新但没有被线程和主线程写入主存储器。线程调度程序取消调度它,其他线程获得锁并更新主内存中的变量。 Is there any info. 是否有任何信息。 in JLS regarding the same? 在JLS中是否一样?

Is it possible for the thread scheduler to unschedule a thread holding [a lock]? 线程调度程序是否可以取消对持有[锁]的线程的调度?

Yes, that can happen preemptively in many scheduling algorithms . 是的,这可以在许多调度算法中抢先发生。 It must happen if the thread makes a blocking system call (eg, to wait for input). 如果线程进行了阻塞的系统调用(例如,等待输入),则必须发生这种情况。

If yes then does the unscheduling leads to thread releasing the lock? 如果是,那么非调度导致线程释放锁吗?

Absolutely not! 绝对不! That would defeat the purpose of locking, and it would break most multi-threaded programs. 那会破坏锁定的目的,并且会破坏大多数多线程程序。


Takeaway: Keep your critical sections as short as possible! 要点:关键部分要尽量短! Don't let threads B, C, D, and E all get blocked waiting for thread A to release some lock when thread A is blocked performing a long computation (or worse, waiting for input). 当线程A被阻塞执行较长的计算(或更糟糕的是,等待输入)时,不要让线程B,C,D和E都被阻塞,等待线程A释放一些锁。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM