qt mutex lock

1. Atomic operations

According to the compilation principle, for example, processing a piece of data requires three steps: data is transmitted, processed, and sent back. Each step is indivisible and requires one clock cycle to complete, so such a one-step operation is an atomic operation.
Conversely, the command to process a piece of data is not an atomic operation, and the commands we write in high-level languages ​​such as C++ are often not atomic operations.

2. Mutex lock

Multithreading always needs to consider mutual exclusion. For example, when writing a log file, log information from different threads compete with each other to write the file, then a mutex lock must be added to the file writing, but you cannot simply add a flag=1 in front, because the flag=1 command It is not an atomic operation, and it takes several steps to be reflected to the bottom layer. Just imagine that the next thread will make a judgment before the flag=1 command of the previous thread has been completed. Then both of them may enter the mutually exclusive part. Therefore, adding a mutex lock must be an atomic operation.

3. Comparison of two mutex locks in Qt

Mutex implementations in qt include QMutex and QMutexLocker

1. QMutex usage

This class uses lock() and unlok() to complete the operation of protecting the critical section.

QMutex mutex;
int a_b(int a,int b){
    mutex.lock();
    a+=2;
    b+=3;
    mutex.unclock();
    return a+b;
    }

The above code is an example of QMutex. After analysis, it is found that there may be a problem: it is unlocked before return, and the second thread may enter the critical section before the first thread returns; then if the unlock is placed in It doesn't work after the return, because then the unlocking code will not be executed.

  1. Use of QMutexLocker
QMutex mutex;
int a_b(int a,int b){
    QMutexLocker lock(&mutex);
    a+=2;
    b+=3;
    return a+b;
    }

As you can see from the above code, QMutexLocker only needs to be created before the critical section starts. It no longer needs a line of unlocking code, because its unlocking is in the destructor of the critical section function, which means that when the function a_b is executed, it exits. The scope will be unlocked synchronously.
So QMutexLocker is simpler and less error-prone

Guess you like

Origin blog.csdn.net/qq_41104439/article/details/128204030