What is a mutex? How to use mutex?

1. What is a mutex?

Mutex is a synchronization primitive used in multithreaded programming to ensure mutual exclusion when multiple threads access shared resources .

In a multi-threaded environment, when multiple threads access shared resources at the same time, it may cause data competition and inconsistency. To avoid this kind of problem, you need to ensure that only one thread can access the shared resource at any time, while other threads need to wait until the resource is available .

Mutual exclusion locks provide such a mechanism that when a thread accesses a shared resource, it has a mutual exclusion lock, and other threads need to wait for the release of the mutex lock to access the shared resource. Once a thread finishes accessing the shared resource, it releases the mutex so that other threads can acquire the mutex and access the shared resource.

2. The basic operation of a mutex includes two important steps: locking and unlocking

Lock: When a thread needs to access a shared resource, it tries to acquire a mutex. If the mutex is not currently held by other threads, then the thread can acquire the mutex and continue to execute code that accesses shared resources. If the mutex is already held by another thread, the thread will enter a blocked state, waiting for the release of the mutex.

Unlock (Unlock): When a thread finishes accessing the shared resource, it releases the mutex so that other threads can acquire the mutex and access the shared resource.

3. Sample code

main.cpp

#include <iostream>
#include <thread>
#include <mutex>

std::mutex mtx;
int sharedResource = 0;

void increment()
{
    for (int i=0; i<5; ++i){
        std::lock_guard<std::mutex> lock(mtx); // 使用 std::lock_guard 创建互斥锁的作用域,确保每次只有一个线程可以访问 sharedResource
        sharedResource++;
        std::cout << "Increatmented, value: " << sharedResource << std::endl;
    } // 在作用域结束时,std::lock_guard 会自动释放互斥锁
}

void decrement()
{
    for (int i=0; i< 5; ++i){
        std::lock_guard<std::mutex> lock(mtx);
        sharedResource--;
        std::cout << "Decremented, value: " << sharedResource << std::endl;
    }
}

int main()
{
    // 创建了两个线程 t1 和 t2
    std::thread t1(increment);
    std::thread t2(decrement);
    
    // 等待这两个线程的执行结束
    t1.join();
    t2.join();

    std::cout << "Final shared resource value: " << sharedResource << std::endl;

    return 0;
}

CmakeList.txt

cmake_minimum_required(VERSION 3.5)

project(untitled2 LANGUAGES CXX)

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
find_package(Threads REQUIRED)
add_executable(untitled2 main.cpp)

#include(GNUInstallDirs)
#install(TARGETS untitled2
#    LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
#    RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
#)



target_link_libraries(untitled2 Threads::Threads)

program output

23:12:22: Starting /home/lrj/build-untitled2-Desktop_Qt_5_15_2_GCC_64bit-Debug/untitled2...
Increatmented, value: 1
Increatmented, value: 2
Increatmented, value: 3
Increatmented, value: 4
Increatmented, value: 5
Decremented, value: 4
Decremented, value: 3
Decremented, value: 2
Decremented, value: 1
Decremented, value: 0
Final shared resource value: 0
23:12:22: /home/lrj/build-untitled2-Desktop_Qt_5_15_2_GCC_64bit-Debug/untitled2 退出,退出代码: 0

It can be seen from the output information that when increment accesses shared resources, decrement is blocked.

Guess you like

Origin blog.csdn.net/weixin_45824067/article/details/132067750