Joke Collection Website - Joke collection - What is the principle of thread locking?

What is the principle of thread locking?

The principle of thread lock: When an object obtains a lock, it first invalidates its own cache, thus ensuring that variables can be loaded directly from main memory. ?

Similarly, before an object releases the lock, it flushes its cache, forcing any changes it makes to appear in main memory. In this way, it can be guaranteed that two threads synchronized on the same lock will see the same value of the variable modified in the synchronization block.

Generally speaking, threads are not constrained by cache variable values and do not need to be immediately visible to other threads (whether these threads are in registers, in processor-specific caches, or through instruction reordering or other compiler optimizations).

Extended information: Thread lock uses QMutex in the run () function to achieve synchronization. When multiple threads access * * * shared variables, lock/trylock and unlock are used to wrap * * * shared variables to ensure synchronous access to * * * shared variables.

If you don't lock it, modifying the num variable at the same time after 2 seconds will cause the thread not to execute according to our idea. After the current thread is locked, other threads will wait for unlocking if they encounter * * * variables;

When using QMutex to lock and unlock, unlock () may not be executed when the code exits early. If other threads use lock to lock, it will always be blocked, resulting in memory overflow.