In effect it borrows time from the main VCL thread to do this. This doesn't work arbitrarily between threads. If you have two non-VCL threads, X and Y, you can't call synchronize in X alone and then modify data stored in Y. It is necessary to call synchronize from both threads when reading or writing the shared data. In effect, this means that the data is modified by the main VCL thread, and all the other threads synchronize to the main VCL thread every time they need to access this data. This is workable, but inefficient, especially if the main thread is busy: every time the two threads need to communicate, they have to wait for a third thread to become idle. Later on, we shall see how to control concurrency between the threads and have them communicate directly.
TThread.Synchronize可以避免线程对共享数据访问时发生冲突,它的实现方法是,当子线程利用Synchronize方法执行访问共享资源的代码时,该子线程立刻挂起,等待主线程空闲后在主线程中执行该访问共享资源的代码,代码在主线程执行完后,主线程回复原始状态,而子线程继续运行。 概括来说,子线程中的代码实际是在主线程中执行的,实质为给主线程发了个消息,通知它应该调用哪个函数。
存在的问题是,当多个子线程之间要同步时, 按此方法,必须等待主线程空闲下来,才有机会获得在主线程中的运行权,这就显得没有必要,效率也低。