Home > Backend Development > C++ > body text

How to deal with shared resources in multi-threading in C++?

WBOY
Release: 2024-06-03 10:28:57
Original
972 people have browsed it

Use mutex (mutex) in C++ to handle multi-threaded shared resources: create a mutex through std::mutex. Use mtx.lock() to obtain a mutex for exclusive access to shared resources. Use mtx.unlock() to release the mutex.

How to deal with shared resources in multi-threading in C++?

Handling shared resources in multi-threading in C++

Introduction

In In multi-threaded programming, when multiple threads access shared resources concurrently, thread safety issues will arise. Mutex (mutex) is a synchronization mechanism that ensures that only one thread accesses shared resources at the same time, thereby preventing data competition and corruption.

The syntax and usage of mutex

In C++, you can use std::mutex to create a mutex:

std::mutex mtx;
Copy after login

To have exclusive access to shared resources, you need to use lock() and unlock() Methods:

mtx.lock(); // 获取互斥量
// 对共享资源进行操作
mtx.unlock(); // 释放互斥量
Copy after login

Practical case

The following is a practical case of using a mutex to protect shared resources:

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

std::mutex mtx;
int shared_resource = 0;

void increment_resource() {
    mtx.lock();
    shared_resource++;
    mtx.unlock();
}

int main() {
    std::vector<std::thread> threads;

    // 创建多个线程并行执行 increment_resource() 函数
    for (int i = 0; i < 1000; i++) {
        threads.push_back(std::thread(increment_resource));
    }

    // 等待所有线程执行完毕
    for (auto& thread : threads) {
        thread.join();
    }

    // 打印共享资源的最终值,此时的值应该是 1000
    std::cout << shared_resource << std::endl;

    return 0;
}
Copy after login

The above is the detailed content of How to deal with shared resources in multi-threading in C++?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!