Because Process/There are many methods for synchronizing data between threads. Each method has different purposes:Critical Section,Mutex, Signal lights, events for synchronization.
Because the process/Operations between threads are performed in parallel, so a data synchronization problem occurs. Let's look at a piece of code first:
Int iCounter = 0; // global variable
DOWRD threadA (void * pD)
{
For (int I = 0; I <100; I ++)
{
Int iCopy = iCounter;
// Sleep (1, 1000 );
ICopy ++;
// Sleep (1, 1000 );
ICounter = iCopy;
}
}
Now we assume there are two threads.When threadA1 and threadA2 are running at the same time, what is the iCounter value after the execution is completed? Is it 200? No. If we remove the comments before Sleep (1000), we can easily understand this problem, because it may have been modified by other threads before the iCounter value is correctly modified. This example is an example of enlarging machine code operations, because the CPU also goes through the data read/write process, in the process of thread execution, the thread may be interrupted and other threads can execute it. After the variable iCounter is modified by the first thread and written back to the memory, if it is read by the second thread, it is written back by the first thread, the second thread actually reads the wrong data, which is called dirty read ). This example can also be used to use files and resources.
So how can we avoid this problem? Suppose we are usingICounter asked other threads: who is using it? If not, you can operate the variable immediately. Otherwise, you can use the variable after other threads are used up, in addition, other threads cannot use this variable after they have obtained control of the variable until they have used it and released it. The modified pseudocode is as follows:
Int iCounter = 0; // global variable
DOWRD threadA (void * pD)
{
For (int I = 0; I <100; I ++)
{
Ask to lock iCounter
Wait other thread release the lock
Lock successful