问题
I tested the following code with the Synchronize()
method in C++Builder 2010:
while(true) {}
CreateDirectory ("D:\\test", NULL);
What happened is that the UI freezed, and the folder was not created. Does that means that Synchronize()
passes the code to the UI thread to execute it, and then waits until the code is executed before continuing?
Edit:
I explained wrongly what I have done in my test code. What I have really done is the following:
I called Synchronize()
with the following code:
while(true) {}
And after calling Synchronize()
, I had the following code:
CreateDirectory ("D:\\test", NULL);
回答1:
Does that means that Synchronize() passes the code to the UI thread to execute it, and then waits until the code is executed before continuing?
Yes. This is in fact described in the documentation:
Executes a method call within the main thread.
Synchronize causes the call specified by AMethod to be executed using the main thread, thereby avoiding multithread conflicts. The AThread parameter associates the caller thread.
For static methods, you can associate AMethod with any thread using the AThread parameter. Also, you can use nil/NULL as AThread parameter if you do not need to know the information for the caller thread in the main thread.
In the current implementation, the Synchronize method can use associated thread information to wake-up the main thread on Windows platforms.
If you are unsure whether a method call is thread-safe, call it from within the Synchronize method to ensure that it executes in the main thread.
Execution of the current thread is suspended while the method executes in the main thread.
Your infinite loop is therefore blocking the main thread. And indeed the worker thread.
来源:https://stackoverflow.com/questions/29686543/how-does-tthread-synchronize-work