Understanding TCriticalSection and Synchronize
SendMessage suspends currently executing thread (as well as any other thread).
No, that is incorrect. SendMessage
does not suspend anything. SendMessage merely delivers a message synchronously. The function does not return until the message has been delivered. That is, the window proc of the target window has been executed. And because the window proc is always called on the thread that owns the window, this means that the calling thread may need to be blocked to wait until the window's owning thread is ready to execute the window proc. It most definitely doesn't suspend all threads in the process.
How does the critical section know that I am protecting
MyVariable1
?
It doesn't. It's entirely up to you to make sure that all uses of MyVariable1
that need protection, are given protection. A critical section is a form of mutex. A mutex ensures that only one thread of execution can hold the mutex any any instant in time.
As I call
Acquire()
within all of the threads that might write to this block or use this function.
That's not really it either. The "within all of the threads" is a mis-think. You need to be thinking about "at all sections of code that use the variable".
Does a critical section therefore always need to be a global kind of variable?
No, a critical section can be a global variable. But it need not be.