Home >Backend Development >C++ >What is the purpose of read-write locks in C++ multi-threaded programming?

What is the purpose of read-write locks in C++ multi-threaded programming?

WBOY
WBOYOriginal
2024-06-03 11:16:57827browse

In multi-threading, read-write locks allow multiple threads to read data at the same time, but only allow one thread to write data to improve concurrency and data consistency. The std::shared_mutex class in C provides the following member functions: lock(): Gets write access, succeeds when no other thread holds the read or write lock. lock_read(): Obtain read access permission, which can be held simultaneously with other read locks or write locks. unlock(): Releases write access. unlock_shared(): Releases read access.

C++ 多线程编程中读写锁的用途是什么?

The purpose of read-write locks in C multi-threaded programming

Overview

In multi-threaded programming, read-write lock is a synchronization mechanism that allows multiple threads to read shared data at the same time, but only one thread can write shared data. This helps improve concurrency while ensuring data consistency.

Implementation

The std::shared_mutex class in C implements read-write locks. It provides the following member functions:

  • #lock(): Get write access to the lock. This function succeeds only if no other thread holds the read or write lock.
  • lock_read(): Get read access to the lock. Can be held concurrently with other read or write locks.
  • unlock(): Release locked write access.
  • unlock_shared(): Releases read access to the lock.

Example Usage

Consider the following code, which uses a read-write lock to protect a shared variable:

#include <iostream>
#include <shared_mutex>

std::shared_mutex m;
int shared_var = 0;

void reader() {
    m.lock_read();
    std::cout << "Reading: " << shared_var << '\n';
    m.unlock_shared();
}

void writer() {
    m.lock();
    std::cout << "Writing: " << ++shared_var << '\n';
    m.unlock();
}

int main() {
    std::thread t1(reader);
    std::thread t2(writer);
    std::thread t3(reader);
    t1.join();
    t2.join();
    t3.join();
}

Output:

Reading: 0
Writing: 1
Reading: 1

The above is the detailed content of What is the purpose of read-write locks in C++ multi-threaded programming?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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